const db = require('../db');

const overview = {
    id: 18,
    title: 'Introduction to OSINT',
    description: 'Master Open Source Intelligence gathering techniques and tools.'
};

const tasks = [
    { id: 181, title: 'What is OSINT?' },
    { id: 182, title: 'The Intelligence Cycle' },
    { id: 183, title: 'OPSEC & Sock Puppets' },
    { id: 184, title: 'Google Dorking Mastery' },
    { id: 185, title: 'People & Username Recon' },
    { id: 186, title: 'Email & Breach Data' },
    { id: 187, title: 'Image Intelligence (IMINT)' },
    { id: 188, title: 'Domain & Infrastructure' },
    { id: 189, title: 'Geolocation & Maps' },
    { id: 190, title: 'Module 18 Final Quiz' }
];

const lessons = {
    181: {
        content: `# What is OSINT?

**OSINT (Open Source Intelligence)** is the collection and analysis of data gathered from open sources (publicly available information) to produce actionable intelligence.

## It is NOT Hacking
OSINT allows you to gather data without "touching" the target's servers in a malicious way. You are reading what they published.

## Categories of OSINT
*   **Passive Info**: Reading a LinkedIn profile, checking a DNS record. (No alert generated).
*   **Semi-Passive**: Sending a packet to a server to see if it responds (Port Scan, Shodan).
*   **Active**: Interacting with the target (Social Engineering). OSINT is primarily Passive.

## Sources
*   **Public Government Data**: Tax records, property records.
*   **The Internet**: Social media, forums, blogs.
*   **Grey Literature**: Technical reports, patents, newsletters.
*   **Media**: News reports, TV, Radio.`,
        questions: [
            ['What is the defining characteristic of OSINT?', 'It uses publicly available information', 'Public', ['It uses hacking tools', 'It uses spy satellites', 'It uses publicly available information', 'It is always illegal']],
            ['Is browsing a company\'s public website considered "Hacking"?', 'No, it is Passive OSINT', 'Passive', ['Yes, immediately', 'No, it is Passive OSINT', 'Only if you use Chrome', 'Only if using VPN']],
            ['Which method gives you information without alerting the target?', 'Passive Reconnaissance', 'Quiet', ['Active Scanning', 'Passive Reconnaissance', 'Phishing', 'DDoS']]
        ]
    },
    182: {
        content: `# The Intelligence Cycle

You don't just "Google things". Intelligence follows a process.

## 1. Planning & Direction
*   **Question**: "What are we looking for?" (e.g., "Find the CEO's home address").
*   **Scope**: "What is out of bounds?" (e.g., "Do not contact his family").

## 2. Collection
*   Gathering raw data.
*   **Tools**: Google, Maltego, the Harvester.
*   *Result*: A pile of links, PDFs, and usernames.

## 3. Processing
*   Organizing the data.
*   Translating foreign documents.
*   Decrypting hashes (if found publicly).

## 4. Analysis & Production
*   Connecting the dots.
*   *Insight*: "The CEO uses the username 'CoolGuy99' on Twitter. 'CoolGuy99' also posted on a car forum about his home in Miami." -> **Link Established**.

## 5. Dissemination
*   Writing the report for the client.`,
        questions: [
            ['What is the first step of the Intelligence Cycle?', 'Planning & Direction', 'Goal setting', ['Collection', 'Planning & Direction', 'Analysis', 'Hacking']],
            ['In which phase do you "connect the dots" to form a conclusion?', 'Analysis', 'Thinking', ['Collection', 'Analysis', 'Processing', 'Scanning']],
            ['What is the output of the "Collection" phase?', 'Raw Data', 'Unsorted stuff', ['Finished Report', 'Raw Data', 'Intelligence', 'Arrests']]
        ]
    },
    183: {
        content: `# OPSEC & Sock Puppets

**OPSEC (Operations Security)** is protecting *yourself* while you investigate others.

## The Sock Puppet
A "Sock Puppet" is a fake identity used for research.
*   **Never use your real account**: If you view a target's LinkedIn with your real profile, they get a notification: "Baris viewed your profile." The investigation is burned.
*   **Creation**:
    *   **Name**: Fake name generator.
    *   **Photo**: AI generated face (\`thispersondoesnotexist.com\`) to avoid reverse image search hits.
    *   **Phone**: Burner phone / VoIP for SMS verification.
    *   **Browser**: A dedicated browser container or VM.

## VPN / Proxy
Always hide your IP.
*   If you visit a target's blog, your IP is in their logs.
*   Use a VPN (e.g., ProtonVPN, Mullvad) or Tor.

### Tool Box 🧰
*   **[ThisPersonDoesNotExist](https://thispersondoesnotexist.com)**: Generates AI faces.
*   **[ProtonMail](https://proton.me/mail)**: Encrypted, anonymous email.
*   **[Privacy.com](https://privacy.com)**: Virtual credit cards.`,
        questions: [
            ['What is a "Sock Puppet" in OSINT?', 'A fake online identity', 'Disguise', ['A hand puppet', 'A fake online identity', 'A hacking tool', 'A VPN protocol']],
            ['Why should you verify your VPN before starting?', 'To hide your Source IP from the target', 'Anonymity', ['To make internet faster', 'To hide your Source IP from the target', 'To access Netflix', 'To save battery']],
            ['Why use an AI-generated face for a fake profile?', 'Avoids Reverse Image Search detection', 'Uniqueness', ['It looks better', 'Avoids Reverse Image Search detection', 'Real photos are illegal', 'It is faster']]
        ]
    },
    184: {
        content: `# Google Dorking Mastery

**Google Dorking** (Advanced Search Operators) is the most powerful free OSINT tool.

## Basic Operators
*   \`site:\`: Limit to a domain.
    *   \`site:linkedin.com "Elon Musk"\`
*   \`filetype:\`: Find specific files.
    *   \`site:gov filetype:pdf "deployment"\`
*   \`intitle:\`: Search the page title.
    *   \`intitle:"index of" "backup"\` (Finds open directory listings).
*   \`inurl:\`: Search the URL text.
    *   \`inurl:admin.php\`

## The Cache
*   \`cache:example.com\`: View Google's saved version of a page (useful if the page was deleted).

## Combinations (The "Dork")
*   **Find Passwords**: \`filetype:xlsx site:example.com "password"\`
*   **Find Config Files**: \`filetype:env "DB_PASSWORD"\`
*   **Find ID Cards**: \`intitle:"index of" "passport.jpg"\`

### Tool Box 🧰
*   **[Google Hacking Database (GHDB)](https://www.exploit-db.com/google-hacking-database)**: A massive list of pre-made dorks.
*   **[DorkSearch](https://dorksearch.com/)**: A Dork builder.`,
        questions: [
            ['Which operator restricts results to a specific website?', 'site:', 'Domain limit', ['host:', 'site:', 'www:', 'map:']],
            ['How do you find specifically PDF files?', 'filetype:pdf', 'File extension', ['pdf:', 'filetype:pdf', 'ext:adobe', 'doc:pdf']],
            ['What does `intitle:"index of"` typically reveal?', 'Open Directory Listings', 'A list of files', ['The homepage', 'Open Directory Listings', 'Google Maps', 'DNS records']]
        ]
    },
    185: {
        content: `# People & Username Recon

People are creatures of habit. They reuse usernames across platforms.

## Username Correlation
If a target is \`cool_hacker_99\` on Twitter, they are likely \`cool_hacker_99\` on Instagram, GitHub, and Reddit.

### Tools
*   **[Sherlock](https://github.com/sherlock-project/sherlock)**: A python script that checks a username against 300+ sites.
    *   \`python3 sherlock.py cool_hacker_99\`
*   **[Namechk](https://namechk.com/)**: Web-based version.

## Social Media Archives
Just because they deleted the tweet doesn't mean it's gone.
*   **Wayback Machine**: \`archive.org\`.
*   **Archive.today**: Good for capturing current pages before they change.

### Tool Box 🧰
*   **[Sherlock](https://github.com/sherlock-project/sherlock)**: The King of username enumeration.
*   **[WhatsMyName.app](https://whatsmyname.app/)**: Fast username search.`,
        questions: [
            ['What concept relies on users choosing the same handle everywhere?', 'Username Correlation', 'Reuse', ['Password Reuse', 'Username Correlation', 'Identity Theft', 'Phishing']],
            ['Which tool checks a username across hundreds of sites?', 'Sherlock', 'Detective', ['Nmap', 'Sherlock', 'Wireshark', 'Metasploit']],
            ['If a user deletes a post, where might you still find it?', 'Wayback Machine / Archive', 'Time travel', ['Recycle Bin', 'Wayback Machine / Archive', 'Dark Web', 'Nowhere']]
        ]
    },
    186: {
        content: `# Email & Breach Data

"Breach Data" is the gold mine of OSINT. When sites like LinkedIn or Adobe get hacked, millions of emails and passwords leak.

## Have I Been Pwned (HIBP)
A safe way to check if an email was in a breach. It tells you *which* breach, but doesn't give you the password.
*   **Input**: \`target@example.com\`
*   **Output**: "Pwned in 3 breaches (LinkedIn 2016, Adobe 2013)."

## DeHashed / IntelX
These are "Grey Hat" services (often paid) that allow you to search the *actual* raw data.
*   **Use Case**: You find the target's password was \`Summer2018!\`.
*   **Pivot**: Does he use \`Summer2018!\` on his corporate email? (Password Spraying).

### Tool Box 🧰
*   **[HaveIBeenPwned](https://haveibeenpwned.com)**: The standard for breach checking.
*   **[Hunter.io](https://hunter.io)**: Finds email patterns for companies (e.g., \`first.last@company.com\`).
*   **[Phonebook.cz](https://phonebook.cz)**: Lists all domains and emails for a target URL.`,
        questions: [
            ['What does "HaveIBeenPwned" tell you?', 'If an email was part of a known breach', 'Leak status', ['The user\'s password', 'If an email was part of a known breach', 'The user\'s location', 'The user\'s bank']],
            ['What is Hunter.io primarily used for?', 'Finding corporate email formats', 'Business emails', ['Hacking wifi', 'Finding corporate email formats', 'Tracing phones', 'Buying guns']],
            ['Why is old breach data useful?', 'Password reuse', 'Habits', ['It isn\'t', 'Password reuse', ' blackmail', 'It proves they are dumb']]
        ]
    },
    187: {
        content: `# Image Intelligence (IMINT)

Images contain more than just pixels.

## Reverse Image Search
"Where else does this image exist?"
*   **Google Images**: Good for products.
*   **Yandex Images**: The BEST for faces and locations (Russian search engine, very powerful AI).
*   **TinEye**: Good for exact matches.

## EXIF Data
Metadata hidden inside the file.
*   **GPS Coordinates**: Use \`exiftool\` to see if the photo contains Latitude/Longitude.
*   **Camera Model**: "iPhone 13 Pro".
*   **Timestamp**: When was it actually taken?

### Geolocation Challenges
"Find where this photo was taken."
*   Look for landmarks (Eiffel Tower).
*   Look for text (Street signs, shop names).
*   Look for Sun shadows (Time of day).

### Tool Box 🧰
*   **[Jeffrey's Image Metadata Viewer](http://exif.regex.info/exif.cgi)**: Online EXIF view.
*   **[Yandex Images](https://yandex.com/images/)**: Best for facial rec.
*   **[PimEyes](https://pimeyes.com)**: Terrifyingly accurate facial recognition search.`,
        questions: [
            ['What hidden data in a photo might reveal location?', 'EXIF / GPS Data', 'Metadata', ['Pixels', 'EXIF / GPS Data', 'Color profile', 'File name']],
            ['Which search engine is famous for its facial recognition capabilities?', 'Yandex', 'Russian one', ['Bing', 'DuckDuckGo', 'Yandex', 'Yahoo']],
            ['What does Reverse Image Search help you find?', 'Where else the image appears online', 'Sources', ['The person\'s name', 'Where else the image appears online', 'The camera model', 'The password']]
        ]
    },
    188: {
        content: `# Domain & Infrastructure

Mapping a company's digital footprint.

## WHOIS
The birth certificate of a domain.
*   **Registrar**: GoDaddy, Namecheap.
*   **Owner**: Often "Redacted for Privacy", but old records might show "John Smith, Admin".

## DNS Enumeration
Finding subdomains.
*   \`mail.example.com\`
*   \`dev.example.com\` (Target rich environment!)
*   \`vpn.example.com\`

## Infrastructure Visualization
Map the relationships. "This domain shares an SSL certificate with this other scam domain."

### Tool Box 🧰
*   **[DNSDumpster](https://dnsdumpster.com)**: Maps subdomains and draws a graph.
*   **[Sublist3r](https://github.com/aboul3la/Sublist3r)**: Command line subdomain finder.
*   **[BuiltWith](https://builtwith.com)**: Tells you the tech stack (is it WordPress? React? PHP?).
*   **[Who.is](https://who.is)**: Simple Whois lookup.`,
        questions: [
            ['What record functions as the "birth certificate" of a domain?', 'WHOIS', 'Registration', ['DNS', 'WHOIS', 'SSL', 'HTTP']],
            ['Why do we look for subdomains like "dev.example.com"?', 'Often less secure / testing environments', 'Weak targets', ['They look cool', 'Often less secure / testing environments', 'They represent the CEO', 'They are faster']],
            ['What does "BuiltWith" tell you?', 'The technology stack used', 'Tech', ['Who owns it', 'The technology stack used', 'The password', 'The bugs']]
        ]
    },
    189: {
        content: `# Geolocation & Maps

Sometimes the target is a place, not a person.

## Google Maps / Earth
*   **Street View**: Walk around the target building. Look for cameras, gates, and entrances.
*   **3D View**: Estimate fence height.

## Wigle.net
The database of all Wifi networks.
*   **Scenario**: You know the target's home SSID is "FBI_Surveillance_Van".
*   **Search**: Type "FBI_Surveillance_Van" into Wigle.
*   **Result**: Shows the GPS coordinates where that SSID was seen.

## Shodan (Map View)
Find open webcams or SCADA systems in a specific city.

### Tool Box 🧰
*   **[Google Earth Pro](https://www.google.com/earth/versions/)**: Desktop version allows historical imagery (time travel).
*   **[Wigle.net](https://wigle.net)**: Wifi geolocation database.
*   **[SunCalc](https://suncalc.org)**: Analyze shadows to determine time of day.`,
        questions: [
            ['What tool maps Wifi SSIDs to GPS coordinates?', 'Wigle.net', 'Wifi map', ['Google Maps', 'Wigle.net', 'Shodan', 'WifiCracker']],
            ['What feature of Google Earth helps verify "When" a satellite image was taken?', 'Historical Imagery', 'Timeline', ['Street View', 'Historical Imagery', '3D Buildings', 'Atmosphere']],
            ['How can SunCalc help in IMINT?', 'Determine time of day from shadows', 'Shadows', ['Find the weather', 'Determine time of day from shadows', 'Find solar panels', 'Navigate']]
        ]
    },
    190: {
        content: `# Module 18 Final Quiz

Test your mastery of Open Source Intelligence.

## Instructions
*   **20 Questions**.
*   Covering: Fundamentals, Dorking, People, Tools, and Ethics.

Good Luck, Detective!`,
        questions: [
            // Definitions & Ethics
            ['What does OSINT stand for?', 'Open Source Intelligence', 'Open Source', ['Open Source Intelligence', 'Overseas Intelligence', 'Online Security INTerface', 'Open System Integration']],
            ['Is Passive OSINT illegal?', 'Generally No (accessing public data)', 'No', ['Yes, always', 'Generally No (accessing public data)', 'Only in Europe', 'Only for police']],
            ['What is the best way to protect your identity during research?', 'Use a Sock Puppet and VPN', 'OPSEC', ['Clear cookies', 'Use a Sock Puppet and VPN', 'Use Incognito Mode', 'Ask permission']],

            // Dorking
            ['Which Google Dork finds Excel files?', 'filetype:xlsx', 'Spreadsheet', ['file:excel', 'filetype:xlsx', 'type:xls', 'ext:sheet']],
            ['Which operator searches for text inside the URL?', 'inurl:', 'URL text', ['site:', 'inurl:', 'link:', 'addr:']],
            ['If you want to view a deleted page, what Google operator helps?', 'cache:', 'Snapshot', ['history:', 'cache:', 'old:', 'back:']],

            // Tools (People & Email)
            ['Which tool is best for checking username reuse across 300+ sites?', 'Sherlock', 'Python script', ['Nessus', 'Sherlock', 'John the Ripper', 'Wireshark']],
            ['What service helps you find the email format for a company (e.g., first.last)?', 'Hunter.io', 'Email patterns', ['HaveIBeenPwned', 'Hunter.io', 'Gmail', 'Outlook']],
            ['What does "HaveIBeenPwned" check?', 'If an email is in a known data breach', 'Breaches', ['The email password', 'If an email is in a known data breach', 'If the email is valid', 'Who owns the email']],

            // IMINT & Geo
            ['Which search engine is preferred for facial recognition checks?', 'Yandex', 'Russian AI', ['Bing', 'Google', 'Yandex', 'DuckDuckGo']],
            ['What metadata in a photo provides GPS coordinates?', 'EXIF', 'Tags', ['Pixel', 'EXIF', 'PNG', 'Stenography']],
            ['What tool lets you search for Wifi hotspots by SSID?', 'Wigle.net', 'War driving DB', ['WifiMap', 'Wigle.net', 'Google Wifi', 'NetStumbler']],

            // Infrastructure
            ['What record tells you who owns a domain name?', 'WHOIS', 'Registry', ['DNS', 'WHOIS', 'ARP', 'DHCP']],
            ['What tool visualizes domain infrastructure and subdomains as a graph?', 'DNSDumpster', 'Graph', ['Nmap', 'DNSDumpster', 'Ping', 'Traceroute']],
            ['Why are subdomains like "dev" or "staging" valuable targets?', 'Often have weaker security/config', 'Forgotten', ['They are faster', 'Often have weaker security/config', 'They are public', 'They have more money']],

            // Methodology
            ['What is the "Intelligence Cycle" step where you interpret data?', 'Analysis', 'Reasoning', ['Collection', 'Analysis', 'Planning', 'Filing']],
            ['What is a "Grey Hat" OSINT source?', 'Semi-legal/paid breach data sites', 'DeHashed', ['Government sites', 'Semi-legal/paid breach data sites', 'News sites', 'Libraries']],
            ['Why should you verify "Sock Puppets" with a burner phone?', 'Platforms require SMS verification', '2FA', ['To call the target', 'Platforms require SMS verification', 'To look cool', 'It is cheaper']],
            ['What is "Google Hacking"?', 'Using advanced operators to find sensitive info', 'Dorking', ['Hacking Google servers', 'Using advanced operators to find sensitive info', 'Phishing Google employees', 'Using Chrome']],
            ['What is the primary risk of "Active" recon (like port scanning)?', 'It generates logs/alerts on the target', 'Detection', ['It is slow', 'It generates logs/alerts on the target', 'It costs money', 'Nothing']]
        ]
    }
};

async function createModule18() {
    try {
        console.log('🚀 Creating Module 18: OSINT...\n');

        // Create Module
        console.log(`Processing Module ${overview.id}: ${overview.title}`);
        await db.query(`INSERT INTO modules (id, title, description, display_order, learning_path_id) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), description = VALUES(description), learning_path_id = VALUES(learning_path_id)`, 
            [overview.id, overview.title, overview.description, 18, 2]);

        // Create Tasks
        for (const t of tasks) {
            await db.query(`INSERT INTO tasks (id, module_id, title, is_active, display_order) VALUES (?, ?, ?, 1, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), is_active=1`,
                [t.id, overview.id, t.title, t.id]);
        }

        let totalLessons = 0;
        // Populate Lessons
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            // Clean
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);

            // Insert Content
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 15]);

            // Insert Questions
            for (let j = 0; j < lesson.questions.length; j++) {
                const q = lesson.questions[j];
                const options = q[3] ? JSON.stringify(q[3]) : null;
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, options, case_sensitive) VALUES (?, ?, ?, ?, ?, ?, ?)',
                    [taskId, q[0], q[1], j + 1, q[2], options, 0]);
            }
            totalLessons++;
        }

        console.log(`\n✅ Module 18 (OSINT) Created! (${totalLessons} lessons with Tools)\n`);
        process.exit(0);

    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

createModule18();
