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

const overview = {
    id: 39,
    title: 'Advanced Threat Intelligence',
    description: 'Operationalize threat intel: Collection, analysis, dissemination, and integration.',
    learning_path_id: 4
};

const tasks = [
    { id: 391, title: 'Threat Intel Lifecycle' },
    { id: 392, title: 'Collection & Sources' },
    { id: 393, title: 'Analysis & Attribution' },
    { id: 394, title: 'STIX/TAXII & Sharing' },
    { id: 395, title: 'Operationalizing Intel' },
    { id: 396, title: 'Final Quiz' }
];

const lessons = {
    391: {
        content: `# Threat Intel Lifecycle

Threat Intelligence is actionable information about adversaries.

## The Intelligence Cycle
\`\`\`
Planning → Collection → Processing → Analysis → Dissemination → Feedback
     ↑                                                              |
     └──────────────────────────────────────────────────────────────┘
\`\`\`

## Intel Types by Audience
| Type | Audience | Content |
|------|----------|---------|
| **Strategic** | Executives | Trends, threat landscape, risk |
| **Tactical** | Defenders | TTPs, attack methodologies |
| **Operational** | SOC/IR | Active campaigns, IOCs |
| **Technical** | Tools | Hashes, IPs, domains, YARA |

## Key Metrics
*   **Timeliness**: Is intel delivered before the attack?
*   **Accuracy**: Are the IOCs reliable?
*   **Relevance**: Does it apply to our industry/tech stack?
*   **Actionability**: Can we do something with it?`,
        questions: [
            ['Who consumes Strategic threat intel?', 'Executives (high-level trends, risk)', 'Leadership', ['SOC Analysts', 'Executives (high-level trends, risk)', 'Developers', 'Interns']],
            ['What does "Actionability" mean for intel?', 'Can we do something with this information?', 'Useful', ['Is it expensive', 'Can we do something with this information?', 'Is it pretty', 'Is it long']],
            ['Technical intel contains:', 'Hashes, IPs, domains, YARA rules', 'IOCs', ['Strategy documents', 'Hashes, IPs, domains, YARA rules', 'Financial reports', 'HR data']]
        ]
    },
    392: {
        content: `# Collection & Sources

Intel is only as good as its sources.

## Source Types
*   **Open Source (OSINT)**: Public info, news, social media.
*   **Commercial Feeds**: Recorded Future, Mandiant, CrowdStrike.
*   **Government/ISAC**: FBI, CISA, sector-specific ISACs.
*   **Internal**: Your own incidents, logs, honeypots.
*   **Dark Web**: Forums, marketplaces (high risk, high value).
*   **Technical**: Malware sandboxes, passive DNS.

## Key Platforms
| Platform | Type |
|----------|------|
| **VirusTotal** | File/URL intel |
| **Shodan** | Internet-exposed assets |
| **GreyNoise** | Background noise vs targeted |
| **AlienVault OTX** | Community IOC sharing |
| **MISP** | Open-source threat intel platform |

## Collection Tradecraft
*   **Pivoting**: One IOC leads to related infrastructure.
*   **Passive DNS**: Historical domain → IP mappings.
*   **Certificate Transparency**: Find C2 domains via certs.`,
        questions: [
            ['What is MISP?', 'Open-source threat intel sharing platform', 'Platform', ['A SIEM', 'Open-source threat intel sharing platform', 'A firewall', 'A sandbox']],
            ['What does GreyNoise help distinguish?', 'Background internet noise vs targeted attacks', 'Filter', ['Good vs bad files', 'Background internet noise vs targeted attacks', 'Encrypted vs clear', 'Fast vs slow']],
            ['What is "Pivoting" in threat intel?', 'Using one IOC to discover related infrastructure', 'Connect', ['Turning around', 'Using one IOC to discover related infrastructure', 'Deleting IOCs', 'Renaming IOCs']]
        ]
    },
    393: {
        content: `# Analysis & Attribution

Turn raw data into actionable intelligence.

## Analysis Techniques
*   **Diamond Model**: Adversary ↔ Infrastructure ↔ Capability ↔ Victim.
*   **Kill Chain Mapping**: Map intel to Lockheed Martin phases.
*   **MITRE ATT&CK Mapping**: Identify techniques used.
*   **Campaign Tracking**: Group related activity over time.

## Attribution Challenges
*   **False Flags**: Attackers plant indicators pointing to others.
*   **Shared Tools**: Multiple groups use same malware.
*   **Proxy Infrastructure**: VPNs, Tor, compromised hosts.
*   **Operational Security**: Good actors hide their tracks.

## Confidence Levels
| Level | Meaning |
|-------|---------|
| **High** | Multiple corroborating sources |
| **Moderate** | Some corroboration, some gaps |
| **Low** | Single source, speculation |

## Analytic Tradecraft
*   Consider alternative hypotheses.
*   Document assumptions.
*   Separate observation from inference.`,
        questions: [
            ['What is the Diamond Model used for?', 'Relating Adversary, Infrastructure, Capability, and Victim', 'Framework', ['File analysis', 'Relating Adversary, Infrastructure, Capability, and Victim', 'Network monitoring', 'Encryption']],
            ['Why is attribution difficult?', 'False flags, shared tools, proxy infrastructure', 'Challenges', ['It is easy', 'False flags, shared tools, proxy infrastructure', 'Everyone signs their work', 'Logs are perfect']],
            ['What does "High Confidence" attribution mean?', 'Multiple corroborating sources support it', 'Verified', ['Guessing', 'Multiple corroborating sources support it', 'One source', 'No evidence']]
        ]
    },
    394: {
        content: `# STIX/TAXII & Sharing

Standards for machine-readable threat intel.

## STIX (Structured Threat Information eXpression)
*   JSON format for describing threats.
*   Objects: Indicator, Malware, Campaign, Threat Actor, Attack Pattern.
*   Relationships: "uses", "targets", "attributed-to".

## STIX Example
\`\`\`json
{
  "type": "indicator",
  "id": "indicator--8e2e2d2b-17d4-4cbf-938f-98ee46b3cd3f",
  "pattern": "[file:hashes.MD5 = 'd41d8cd98f00b204e9800998ecf8427e']",
  "valid_from": "2024-01-01T00:00:00Z",
  "labels": ["malicious-activity"]
}
\`\`\`

## TAXII (Trusted Automated eXchange of Intelligence Information)
*   Transport protocol for STIX.
*   **Collections**: Server hosts intel feeds.
*   **Channels**: Publish/subscribe model.

## Sharing Communities
*   **ISACs**: Industry-specific (FS-ISAC, Health-ISAC).
*   **ISAOs**: Cross-sector.
*   **TLP (Traffic Light Protocol)**: RED, AMBER, GREEN, WHITE.`,
        questions: [
            ['What is STIX?', 'JSON format for describing threat intelligence', 'Format', ['A transport protocol', 'JSON format for describing threat intelligence', 'A firewall', 'A SIEM']],
            ['What does TAXII do?', 'Transport STIX-formatted threat intel', 'Transport', ['Store files', 'Transport STIX-formatted threat intel', 'Encrypt data', 'Delete IOCs']],
            ['What does TLP:RED mean?', 'Not for disclosure outside the recipient', 'Restricted', ['Public', 'Not for disclosure outside the recipient', 'Community share', 'Partner share']]
        ]
    },
    395: {
        content: `# Operationalizing Intel

Intel is useless if it doesn't improve your defenses.

## Integration Points
| System | How to Use Intel |
|--------|-----------------|
| **SIEM** | Watchlists, correlation rules |
| **Firewall** | Block malicious IPs/domains |
| **EDR** | IOC matching on endpoints |
| **Email Gateway** | Block malicious senders/attachments |
| **Proxy** | Block malicious URLs |
| **SOAR** | Automated enrichment playbooks |

## Automation Pipeline
\`\`\`
Intel Feed → MISP → TIP/SOAR → Push to SIEM/Firewall
                         ↓
                   Enrich with context (confidence, tags)
\`\`\`

## Measuring Effectiveness
*   **Hit Rate**: How often does intel match real threats?
*   **Coverage**: What % of incidents had prior intel?
*   **Time to Integrate**: How fast is new intel deployed?

## Feedback Loop
*   Intel team needs to know if IOCs were useful.
*   Analysts report false positives back to sources.`,
        questions: [
            ['Where can you push IOCs for blocking?', 'Firewall, Proxy, EDR, Email Gateway', 'Enforcement', ['Nowhere', 'Firewall, Proxy, EDR, Email Gateway', 'Only SIEM', 'Only Email']],
            ['What is a TIP?', 'Threat Intelligence Platform', 'Platform', ['Threat Inspection Protocol', 'Threat Intelligence Platform', 'Technical Investigation Process', 'None']],
            ['Why is a feedback loop important?', 'Intel team learns if IOCs were useful or false positives', 'Improve', ['It is not', 'Intel team learns if IOCs were useful or false positives', 'To delete intel', 'To create more alerts']]
        ]
    },
    396: {
        content: `# Final Quiz

Test your Advanced Threat Intelligence knowledge.`,
        questions: [
            ['Who consumes Strategic intel?', 'Executives', 'Leadership', ['SOC Analysts', 'Executives', 'Developers', 'All']],
            ['What is MISP?', 'Open-source threat intel platform', 'Platform', ['SIEM', 'Open-source threat intel platform', 'Firewall', 'EDR']],
            ['STIX is a:', 'JSON format for threat intel', 'Format', ['Transport protocol', 'JSON format for threat intel', 'Firewall rule', 'Log format']],
            ['TAXII is a:', 'Transport protocol for STIX', 'Transport', ['Data format', 'Transport protocol for STIX', 'SIEM', 'EDR']],
            ['What does TLP:RED mean?', 'Not for disclosure outside recipient', 'Restricted', ['Public', 'Not for disclosure outside recipient', 'Share widely', 'Community only']],
            ['Where do you push IOCs for enforcement?', 'Firewall, Proxy, EDR', 'Block', ['Only SIEM', 'Firewall, Proxy, EDR', 'Nowhere', 'Email only']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 39: Advanced Threat Intelligence...\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', 20]);
            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 39 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
