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

const overview = {
    id: 40,
    title: 'Red vs Blue Team Dynamics',
    description: 'Purple teaming: Collaboration between offensive and defensive security.',
    learning_path_id: 4
};

const tasks = [
    { id: 401, title: 'Red, Blue, and Purple Teams' },
    { id: 402, title: 'Red Team Operations' },
    { id: 403, title: 'Blue Team Defense' },
    { id: 404, title: 'Purple Team Exercises' },
    { id: 405, title: 'Adversary Emulation' },
    { id: 406, title: 'Final Quiz' }
];

const lessons = {
    401: {
        content: `# Red, Blue, and Purple Teams

Security is not just defense; it's a continuous battle.

## Red Team
*   **Role**: Offensive. Simulate real-world attacks.
*   **Goal**: Test defenses by attempting to breach them.
*   **Mindset**: "How would an attacker get in?"

## Blue Team
*   **Role**: Defensive. Detect and respond to attacks.
*   **Goal**: Protect assets, detect intrusions, respond to incidents.
*   **Mindset**: "How do we stop the attacker?"

## Purple Team
*   **Role**: Collaboration between Red and Blue.
*   **Goal**: Improve detection by sharing attack knowledge.
*   **Mindset**: "Let's learn together."

## Why Purple Matters
*   Red finds gaps → Blue fixes them.
*   Blue shares visibility → Red understands detection capabilities.
*   Continuous improvement through adversarial collaboration.`,
        questions: [
            ['What is the Red Team\'s primary role?', 'Offensive - simulate attacks to test defenses', 'Offense', ['Defensive', 'Offensive - simulate attacks to test defenses', 'Compliance', 'Training']],
            ['What is Purple Teaming?', 'Collaboration between Red and Blue teams', 'Collab', ['Only offense', 'Collaboration between Red and Blue teams', 'Only defense', 'Management']],
            ['Why does Purple Teaming improve security?', 'Red shares attack methods, Blue improves detection', 'Learn together', ['It is cheaper', 'Red shares attack methods, Blue improves detection', 'More alerts', 'Less work']]
        ]
    },
    402: {
        content: `# Red Team Operations

Think like an attacker to defend better.

## Red Team Lifecycle
1.  **Reconnaissance**: OSINT, footprinting, social engineering recon.
2.  **Weaponization**: Build payloads, C2 infrastructure.
3.  **Delivery**: Phishing, watering hole, physical access.
4.  **Exploitation**: Gain initial access.
5.  **Post-Exploitation**: Persistence, lateral movement, privilege escalation.
6.  **Objective**: Data exfiltration, ransomware simulation, domain admin.

## Key Tools
| Tool | Purpose |
|------|---------|
| **Cobalt Strike** | Commercial C2 framework |
| **Metasploit** | Exploitation framework |
| **Impacket** | Network protocol attacks |
| **BloodHound** | AD attack path mapping |
| **Responder** | LLMNR/NBT-NS poisoning |
| **Mimikatz** | Credential extraction |

## Rules of Engagement (ROE)
*   Scope: What's in/out?
*   Timing: Business hours or 24/7?
*   Escalation: When to notify Blue?
*   Safety: No denial of service unless approved.`,
        questions: [
            ['What is an ROE in Red Team context?', 'Rules of Engagement - defines scope and limits', 'Rules', ['A tool', 'Rules of Engagement - defines scope and limits', 'A C2 framework', 'A report']],
            ['Which tool is used for AD attack path mapping?', 'BloodHound', 'Graph', ['Metasploit', 'BloodHound', 'Cobalt Strike', 'Nmap']],
            ['What is post-exploitation?', 'Actions after initial access (persistence, lateral movement)', 'After', ['Before hacking', 'Actions after initial access (persistence, lateral movement)', 'Cleanup', 'Reporting']]
        ]
    },
    403: {
        content: `# Blue Team Defense

Detect, contain, and eradicate threats.

## Blue Team Capabilities
*   **Detection**: SIEM, EDR, NDR, threat hunting.
*   **Response**: IR playbooks, containment, forensics.
*   **Prevention**: Hardening, patching, segmentation.
*   **Recovery**: Restore from backup, rebuild systems.

## Detection Engineering
*   Write detections for known Red Team tactics.
*   Use MITRE ATT&CK to map coverage gaps.
*   Continuously test detections with atomic tests.

## Key Defensive Technologies
| Technology | Purpose |
|------------|---------|
| **SIEM** | Log aggregation, correlation |
| **EDR** | Endpoint visibility, response |
| **NDR** | Network traffic analysis |
| **SOAR** | Automated response |
| **Deception** | Honeypots, honeytokens |

## Metrics for Blue Team
*   **MTTD**: Mean Time to Detect.
*   **MTTR**: Mean Time to Respond.
*   **Coverage**: % of ATT&CK techniques detected.`,
        questions: [
            ['What does NDR focus on?', 'Network Detection and Response', 'Network', ['Endpoints', 'Network Detection and Response', 'Email', 'Cloud']],
            ['What is a honeytoken?', 'Fake credential or data designed to alert on access', 'Trap', ['Real password', 'Fake credential or data designed to alert on access', 'A log file', 'A backup']],
            ['How does Blue Team use MITRE ATT&CK?', 'Map detection coverage and identify gaps', 'Coverage', ['Attack systems', 'Map detection coverage and identify gaps', 'Delete logs', 'Train users']]
        ]
    },
    404: {
        content: `# Purple Team Exercises

Structured collaboration between offense and defense.

## Exercise Types
*   **Atomic Tests**: Single technique execution, immediate detection validation.
*   **Attack Simulations**: Multi-stage attack chain.
*   **Tabletop Exercises**: Discussion-based, no live attacks.
*   **Full Purple Team**: Red executes, Blue hunts in real-time.

## Workflow
1.  **Select Technique**: Pick from ATT&CK (e.g., T1055 Process Injection).
2.  **Red Executes**: Run the technique in a controlled way.
3.  **Blue Hunts**: Try to detect with existing tools.
4.  **Debrief**: Did Blue detect? Why/why not?
5.  **Improve**: Create new detection, tune rules.
6.  **Document**: Update detection coverage map.

## Communication
*   Real-time Slack/Teams channel.
*   Screen sharing during execution.
*   Post-exercise report with findings.

## Success Metrics
*   Detection created for each technique tested.
*   Time to detect improved.
*   Collaboration across silos.`,
        questions: [
            ['What is an Atomic Test?', 'Single technique execution with immediate validation', 'Small test', ['Full attack simulation', 'Single technique execution with immediate validation', 'Discussion only', 'Report writing']],
            ['During Purple Team, what happens if Blue fails to detect?', 'Create new detection rule or tune existing', 'Improve', ['Blame Red', 'Create new detection rule or tune existing', 'Ignore it', 'Delete logs']],
            ['Why is real-time communication important in Purple Team?', 'Blue can correlate activity in real-time', 'Immediate', ['It is not', 'Blue can correlate activity in real-time', 'For fun', 'To delay']]
        ]
    },
    405: {
        content: `# Adversary Emulation

Replicate real threat actor behavior.

## What is Adversary Emulation?
*   Go beyond generic pen testing.
*   Replicate specific threat actor TTPs.
*   Test against realistic adversary behavior.

## Resources
*   **MITRE ATT&CK**: Threat actor profiles with techniques.
*   **Threat Intel Reports**: Mandiant, CrowdStrike annual reports.
*   **APT Groups**: APT29, APT28, Lazarus, FIN7.

## Emulation Frameworks
| Framework | Description |
|-----------|-------------|
| **MITRE Caldera** | Automated adversary emulation platform |
| **Atomic Red Team** | Library of technique tests |
| **Red Canary** | Detection validation framework |
| **Infection Monkey** | Breach & attack simulation |

## Example: Emulate APT29
1.  Research APT29 TTPs (MITRE ATT&CK).
2.  Map their techniques: Spearphishing, PowerShell, Mimikatz, C2.
3.  Execute chain in controlled environment.
4.  Validate Blue Team detection at each step.

## Benefits
*   Realistic threat simulation.
*   Prioritize defenses against relevant adversaries.
*   Prove ROI of security investments.`,
        questions: [
            ['What is the difference between pen testing and adversary emulation?', 'Adversary emulation replicates specific threat actor TTPs', 'Realistic', ['No difference', 'Adversary emulation replicates specific threat actor TTPs', 'Pen testing is better', 'Emulation is cheaper']],
            ['Which framework automates adversary emulation?', 'MITRE Caldera', 'Automated', ['Metasploit', 'MITRE Caldera', 'Wireshark', 'Splunk']],
            ['Why emulate a specific APT group?', 'Test defenses against adversaries likely to target you', 'Relevance', ['For fun', 'Test defenses against adversaries likely to target you', 'It is required', 'To impress management']]
        ]
    },
    406: {
        content: `# Final Quiz

Test your Red vs Blue Team knowledge.`,
        questions: [
            ['What is the Red Team\'s goal?', 'Test defenses by simulating attacks', 'Offense', ['Build tools', 'Test defenses by simulating attacks', 'Write reports', 'Train users']],
            ['What is Purple Teaming?', 'Collaboration between Red and Blue', 'Together', ['Only offense', 'Collaboration between Red and Blue', 'Only defense', 'Compliance']],
            ['Which tool extracts Windows credentials?', 'Mimikatz', 'Creds', ['BloodHound', 'Mimikatz', 'Cobalt Strike', 'Nmap']],
            ['What is a honeytoken?', 'Fake data that alerts when accessed', 'Trap', ['Password', 'Fake data that alerts when accessed', 'Log file', 'Backup']],
            ['What framework automates adversary emulation?', 'MITRE Caldera', 'Automation', ['Metasploit', 'MITRE Caldera', 'Wireshark', 'Burp']],
            ['What happens after Blue fails to detect in Purple Team?', 'Create or improve detection rules', 'Improve', ['Blame Red', 'Create or improve detection rules', 'Ignore it', 'Fire someone']]
        ]
    }
};

async function createModule() {
    try {
        console.log('🚀 Creating Module 40: Red vs Blue Team Dynamics...\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 40 Created!\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}
createModule();
