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

const overview = {
    id: 30,
    title: 'Threat Hunting Basics',
    description: 'Proactively search for threats before they cause damage.',
    learning_path_id: 4
};

const tasks = [
    { id: 301, title: 'What is Threat Hunting?' },
    { id: 302, title: 'Hunting vs Detection' },
    { id: 303, title: 'The Hunting Loop' },
    { id: 304, title: 'Hypothesis-Driven Hunting' },
    { id: 305, title: 'Data Sources for Hunting' },
    { id: 306, title: 'Hunting Techniques' },
    { id: 307, title: 'Final Quiz' }
];

const lessons = {
    301: {
        content: `# What is Threat Hunting?

**Threat Hunting** is the proactive search for threats that evade automated detection.

## Reactive vs Proactive
*   **Reactive (SOC)**: Respond to alerts. SIEM says "Alert" -> You investigate.
*   **Proactive (Hunting)**: Assume compromise. Look for threats *before* an alert fires.

## Why Hunt?
*   **Detection Gaps**: No tool catches 100% of attacks.
*   **Dwell Time**: Attackers may hide for months. Average: 21 days.
*   **Advanced Threats**: APTs specifically evade detection.

## Who Hunts?
*   Requires advanced skills (understanding of attack techniques, data analysis).
*   Often a dedicated "Threat Hunter" role or senior SOC analysts.

## The Mindset
*   "Something is wrong; I just haven't found it yet."
*   Be curious, creative, and persistent.`,
        questions: [
            ['What is the difference between SOC and Threat Hunting?', 'SOC reacts to alerts; Hunting proactively searches', 'Proactive', ['No difference', 'SOC reacts to alerts; Hunting proactively searches', 'Hunting is automated', 'SOC is proactive']],
            ['What is "Dwell Time"?', 'Time an attacker stays undetected in the network', 'Hidden', ['Time to read alerts', 'Time an attacker stays undetected in the network', 'Shift duration', 'Lunch break']],
            ['Why are APTs hard to detect?', 'They specifically evade automated detection', 'Stealth', ['They are slow', 'They specifically evade automated detection', 'They use email', 'They are loud']]
        ]
    },
    302: {
        content: `# Hunting vs Detection

## Detection (Automated)
*   Pre-defined rules/signatures.
*   Alerts fire when conditions match.
*   **Example**: SIEM rule: "Alert on 10 failed logins in 1 minute."

## Hunting (Manual/Analytical)
*   No pre-defined rule.
*   Human-driven analysis.
*   **Example**: "Let me look for unusual PowerShell activity across all endpoints this week."

## They Complement Each Other
1.  **Hunt finds new threat** -> Attacker using LOLBin \`certutil\`.
2.  **Create detection rule** -> "Alert when certutil downloads files."
3.  **Detection catches future attacks**.

## Hunting Maturity Model (HMM)
| Level | Description |
|-------|-------------|
| 0 | No hunting, only reactive |
| 1 | Ad-hoc hunts, no process |
| 2 | Regular hunts, some automation |
| 3 | Proactive, hypothesis-driven, documented |
| 4 | Automated hunting, machine learning |`,
        questions: [
            ['Detection relies on what?', 'Pre-defined rules/signatures', 'Rules', ['Guessing', 'Pre-defined rules/signatures', 'Luck', 'Magic']],
            ['What should happen after a successful hunt?', 'Create a detection rule for future attacks', 'Automate', ['Delete logs', 'Create a detection rule for future attacks', 'Ignore it', 'Take vacation']],
            ['At HMM Level 3, hunts are:', 'Proactive and hypothesis-driven', 'Mature', ['Nonexistent', 'Random', 'Proactive and hypothesis-driven', 'Fully automated']]
        ]
    },
    303: {
        content: `# The Hunting Loop

A structured process for threat hunting.

## The Cycle
\`\`\`
┌───────────────────────────────────────────┐
│  1. Hypothesis                            │
│     "I believe attackers are using X"     │
├───────────────────────────────────────────┤
│  2. Collect Data                          │
│     Query SIEM, EDR, logs                 │
├───────────────────────────────────────────┤
│  3. Analyze                               │
│     Look for anomalies, patterns          │
├───────────────────────────────────────────┤
│  4. Investigate                           │
│     Drill into suspicious findings        │
├───────────────────────────────────────────┤
│  5. Report & Improve                      │
│     Document findings, create detections  │
└───────────────────────────────────────────┘
\`\`\`

## Iteration
Even if you find nothing, the hunt is valuable:
*   You learned what "normal" looks like.
*   You refined your hypothesis for next time.`,
        questions: [
            ['What is the first step of the Hunting Loop?', 'Form a Hypothesis', 'Start', ['Collect data', 'Form a Hypothesis', 'Report', 'Delete logs']],
            ['If a hunt finds nothing malicious, was it wasted?', 'No, you learned what normal looks like', 'Value', ['Yes', 'No, you learned what normal looks like', 'Maybe', 'Always']],
            ['What should happen after a hunt?', 'Document findings and create detections', 'Improve', ['Delete evidence', 'Document findings and create detections', 'Forget it', 'Nothing']]
        ]
    },
    304: {
        content: `# Hypothesis-Driven Hunting

**A hypothesis is an educated guess about what threat might exist.**

## Good Hypothesis Examples
*   "Attackers are using encoded PowerShell commands on domain controllers."
*   "Data is being exfiltrated via DNS tunneling."
*   "Phishing campaigns are leading to Cobalt Strike beacon deployment."

## Sources for Hypotheses
*   **Threat Intelligence**: New reports, IOCs.
*   **MITRE ATT&CK**: Techniques used by adversaries.
*   **Internal Incidents**: Past breaches in your org.
*   **Industry Reports**: Attacks on similar companies.

## Bad Hypothesis
*   ❌ "Something bad might happen." (Too vague)
*   ❌ "Check all logs for problems." (No focus)

## MITRE ATT&CK Mapping
*   **Tactic**: What the attacker wants to do (e.g., Execution).
*   **Technique**: How they do it (e.g., T1059 - Command and Scripting Interpreter).
*   Hunt for specific techniques!`,
        questions: [
            ['What makes a good hunting hypothesis?', 'Specific, actionable, based on threat intel', 'Focused', ['Vague and broad', 'Specific, actionable, based on threat intel', 'Random', 'Long']],
            ['Which framework maps attacker techniques?', 'MITRE ATT&CK', 'Framework', ['NIST', 'MITRE ATT&CK', 'ISO 27001', 'PCI DSS']],
            ['What is a bad hypothesis?', 'Something bad might happen (too vague)', 'Unfocused', ['Attackers use PowerShell', 'Something bad might happen (too vague)', 'DNS tunneling exists', 'Phishing leads to C2']]
        ]
    },
    305: {
        content: `# Data Sources for Hunting

**You can only hunt in data you have.**

## Key Data Sources
| Source | What to Look For |
|--------|------------------|
| **EDR** | Process creation, command lines, file writes |
| **SIEM** | Correlated events, authentication logs |
| **Firewall** | Blocked/allowed connections, IPs |
| **Proxy** | URLs visited, user agents |
| **DNS** | Query volume, unusual domains |
| **Active Directory** | Account changes, group memberships |
| **Cloud Logs** | AWS CloudTrail, Azure Activity |

## Data Quality
*   **Completeness**: Are all systems logging?
*   **Retention**: How far back can you look?
*   **Normalization**: Are fields consistent?

## Collection Challenges
*   Logs may be truncated (command line cut off).
*   Some systems don't log by default (enable Sysmon!).
*   Privacy restrictions may limit visibility.`,
        questions: [
            ['Which data source shows process command lines?', 'EDR', 'Endpoint', ['Firewall', 'EDR', 'DNS', 'Proxy']],
            ['What is important about log retention?', 'Determines how far back you can hunt', 'History', ['It is not important', 'Determines how far back you can hunt', 'Makes logs colorful', 'Speeds up queries']],
            ['What tool enhances Windows logging for hunting?', 'Sysmon', 'Windows', ['Wireshark', 'Sysmon', 'Nmap', 'Burp Suite']]
        ]
    },
    306: {
        content: `# Hunting Techniques

## 1. Stack Counting (Frequency Analysis)
*   Count occurrences of a value.
*   Rare = Suspicious.
*   **Example**: Count all User-Agents. "WinHTTP/Evil1.0" appears once -> Investigate.

## 2. Long Tail Analysis
*   Sort by count.
*   Focus on the "long tail" (rare occurrences).
*   Most malware is rare; benign software is common.

## 3. Baseline Comparison
*   Compare current activity to historical baseline.
*   **Example**: "This server normally runs 10 processes; today it has 50."

## 4. Pivot and Drill
*   Start with one indicator.
*   Pivot to related data.
*   **Example**: Suspicious IP -> What internal hosts connected? -> What did those hosts do next?

## 5. Known-Bad Search
*   Search for IOCs from Threat Intelligence.
*   Hash, IP, domain matches.`,
        questions: [
            ['What does "Long Tail Analysis" focus on?', 'Rare occurrences (outliers)', 'Unusual', ['Common events', 'Rare occurrences (outliers)', 'Fast events', 'Old events']],
            ['In "Stack Counting", what is suspicious?', 'Values that appear very rarely', 'Rare', ['Values that appear often', 'Values that appear very rarely', 'All values', 'No values']],
            ['What is "Pivoting" in hunting?', 'Moving from one indicator to related data', 'Connect', ['Rotating chairs', 'Moving from one indicator to related data', 'Deleting logs', 'Blocking IPs']]
        ]
    },
    307: {
        content: `# Final Quiz

Test your Threat Hunting fundamentals.`,
        questions: [
            ['Threat Hunting is:', 'Proactive search for undetected threats', 'Hunt', ['Waiting for alerts', 'Proactive search for undetected threats', 'Deleting logs', 'Writing reports']],
            ['What is "Dwell Time"?', 'Time attacker remains undetected', 'Hidden', ['Time to lunch', 'Time attacker remains undetected', 'Shift length', 'Meeting time']],
            ['A good hypothesis is:', 'Specific and actionable', 'Focused', ['Vague', 'Specific and actionable', 'Random', 'Long']],
            ['What framework maps adversary techniques?', 'MITRE ATT&CK', 'Matrix', ['NIST', 'MITRE ATT&CK', 'ISO', 'PCI']],
            ['Long Tail Analysis focuses on:', 'Rare occurrences', 'Outliers', ['Common events', 'Rare occurrences', 'Fast events', 'All events']],
            ['After finding a threat, you should:', 'Create a detection rule', 'Automate', ['Delete it', 'Create a detection rule', 'Ignore it', 'Hide it']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 30: Threat Hunting Basics...\n');
        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, overview.id, overview.learning_path_id]);
        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), module_id = VALUES(module_id), is_active=1`,
                [t.id, overview.id, t.title, t.id]);
        }
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 15]);
            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]);
            }
        }
        console.log(`✅ Module 30 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
