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

// Efficiently create Path 2 lessons in bulk
async function createPath2Batch() {
    try {
        console.log('🚀 Creating Path 2 Lessons - Batch Mode\n');
        let total = 0;

        // Get all Path 2 tasks
        const tasks = await db.query(`
            SELECT t.id, t.title, t.display_order, m.title as module_title
            FROM tasks t 
            JOIN modules m ON t.module_id = m.id
            WHERE m.learning_path_id = 2
            ORDER BY m.id, t.display_order
        `);

        console.log(`Found ${tasks.rows.length} Path 2 tasks\n`);

        // Template-based lesson creation
        for (const task of tasks.rows) {
            const content = generateLessonContent(task);
            const questions = generateQuestions(task);

            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [task.id, content, 'markdown', 8]);

            for (let i = 0; i < questions.length; i++) {
                await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)',
                    [task.id, questions[i][0], questions[i][1], i + 1, questions[i][2], 0]);
            }

            total++;
            if (total % 10 === 0) console.log(`✓ Created ${total} lessons...`);
        }

        console.log(`\n✅ Path 2 Complete! Created ${total} lessons\n`);

        const totalLessons = await db.query('SELECT COUNT(*) as count FROM lesson_content');
        console.log(`Platform total: ${totalLessons.rows[0].count}/348\n`);

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

function generateLessonContent(task) {
    const module = task.module_title;
    const title = task.title;

    // Generate contextual content based on module
    if (module.includes('Log Analysis')) {
        return `# ${title}

## Overview
Log analysis is fundamental to SOC operations, enabling detection of security incidents through systematic examination of system logs.

## Key Concepts
- **Log Sources**: System logs, application logs, security logs, network logs
- **Log Formats**: Syslog, JSON, CEF, CSV
- **Analysis Techniques**: Pattern matching, correlation, baselining, anomaly detection

## Common Log Types
### System Logs
- Authentication events
- Service starts/stops
- System errors

### Application Logs
- User actions
- Errors and exceptions
- Performance metrics

### Security Logs
- Login attempts
- Access control events
- Security policy violations

## Analysis Tools
- grep, awk, sed (CLI)
- Splunk, ELK Stack (SIEM)
- Python scripts
- Log management platforms

## Best Practices
✅ Centralize logs
✅ Establish baselines
✅ Automate analysis
✅ Retain logs per policy
✅ Protect log integrity

## SOC Workflow
1. Collect logs from sources
2. Normalize different formats
3. Parse and index
4. Correlate events
5. Detect anomalies
6. Alert and investigate

This foundational skill enables effective threat detection and incident response.`;
    }

    if (module.includes('Wireshark')) {
        return `# ${title}

## Overview
Wireshark is the industry-standard network protocol analyzer, essential for deep packet inspection and network troubleshooting.

## Core Capabilities
- Capture live traffic
- Analyze PCAPs
- Protocol dissection
- Traffic filtering
- Stream reconstruction

## Key Features
### Capture Filters
Limit what traffic is captured:
\`\`\`
host 192.168.1.100
port 80
tcp and not port 22
\`\`\`

### Display Filters
Filter captured data for analysis:
\`\`\`
http.request
tcp.flags.syn==1
ip.addr == 10.0.0.1
\`\`\`

## Common Analysis Tasks
- Identify malware communication
- Detect data exfiltration
- Analyze attack patterns
- Troubleshoot connectivity
- Verify encryption

## SOC Use Cases
🔍 Investigate suspicious connections
🔍 Analyze malware traffic
🔍 Identify C2 beaconing
🔍 Detect lateral movement
🔍 Capture attack evidence

## Best Practices
✅ Use capture filters to reduce file size
✅ Save captures for evidence
✅ Follow TCP streams for context
✅ Check protocol hierarchy
✅ Export relevant data

Essential tool for network security analysis and incident investigation.`;
    }

    if (module.includes('IDS/IPS')) {
        return `# ${title}

## Overview
Intrusion Detection and Prevention Systems monitor network traffic for malicious activity and policy violations.

## IDS vs IPS
### Intrusion Detection System (IDS)
- **Passive** monitoring
- Alerts on threats
- No blocking

### Intrusion Prevention System (IPS)
- **Active** protection
- Blocks threats
- In-line deployment

## Detection Methods
### Signature-Based
- Match known attack patterns
- Fast and accurate
- Can't detect new threats

### Anomaly-Based
- Baseline normal behavior
- Detect deviations
- Can find unknown threats
- Higher false positives

### Behavior-Based
- Analyze actions
- Detect policy violations
- Flexible detection

## Popular Solutions
- **Snort** - Open source IDS/IPS
- **Suricata** - Modern, multi-threaded
- **Zeek** (Bro) - Network analysis
- **Commercial**: Palo Alto, Cisco, Fortinet

## Deployment
- **Network**: Monitor traffic
- **Host**: On endpoints
- **Wireless**: WiFi security

## SOC Integration
✓ Alert generation
✓ SIEM integration
✓ Automated response
✓ Threat intelligence feeds

Critical component of defense-in-depth strategy.`;
    }

    // Default template for other modules
    return `# ${title}

## Overview
This lesson covers ${title.toLowerCase()}, an important topic in ${module}.

## Key Concepts
Understanding these fundamentals is essential for security operations:

- Core principles and terminology
- Practical applications in SOC environment
- Best practices and common pitfalls
- Real-world examples and scenarios

## Why This Matters
SOC analysts must master this skill to effectively:
- Detect security incidents
- Investigate threats
- Respond to attacks
- Protect organizational assets

## Tools and Techniques
Common tools and methods used:
- Industry-standard platforms
- Command-line utilities
- Automated analysis tools
- Manual investigation techniques

## Best Practices
✅ Follow established procedures
✅ Document all findings
✅ Collaborate with team
✅ Continue learning
✅ Stay updated on threats

## Application
Apply this knowledge in daily SOC operations for effective security monitoring and incident response.

This foundation enables progression to more advanced security operations concepts.`;
}

function generateQuestions(task) {
    const module = task.module_title;

    // Generate contextual questions
    if (module.includes('Log')) {
        return [
            ['Primary log purpose?', 'Detection', 'Find threats'],
            ['Centralize logs why?', 'Correlation', 'Connect events'],
            ['Log format standard?', 'Syslog', 'Common format'],
            ['Analysis CLI tool?', 'grep', 'Search text'],
            ['Establish normal behavior?', 'Baseline', 'Know normal']
        ];
    }

    if (module.includes('Wireshark')) {
        return [
            ['Packet analyzer tool?', 'Wireshark', 'GUI sniffer'],
            ['Capture file format?', 'PCAP', 'Packet capture'],
            ['Filter captured data?', 'Display filter', 'Post-capture'],
            ['View full conversation?', 'Follow TCP Stream', 'Reconstruct'],
            ['Protocol breakdown?', 'Protocol Hierarchy', 'Statistics']
        ];
    }

    if (module.includes('IDS')) {
        return [
            ['Passive detection?', 'IDS', 'Alert only'],
            ['Active blocking?', 'IPS', 'Prevention'],
            ['Known patterns?', 'Signature', 'Pattern matching'],
            ['Open source IDS?', 'Snort', 'Popular tool'],
            ['Behavior deviation?', 'Anomaly', 'Unusual activity']
        ];
    }

    if (module.includes('Proxy')) {
        return [
            ['Intermediary server?', 'Proxy', 'Between client/server'],
            ['Client-side proxy?', 'Forward', 'User requests'],
            ['Server-side proxy?', 'Reverse', 'Protect backend'],
            ['Cache benefits?', 'Performance', 'Speed up'],
            ['Proxy security?', 'Content filtering', 'Block malicious']
        ];
    }

    if (module.includes('Vulnerability')) {
        return [
            ['Network scanner?', 'Nessus', 'Vulnerability tool'],
            ['Open source scanner?', 'OpenVAS', 'Free option'],
            ['Scan output format?', 'CVE', 'Vulnerability ID'],
            ['Risk priority?', 'CVSS score', 'Severity rating'],
            ['Remediation step?', 'Patch', 'Fix vulnerability']
        ];
    }

    if (module.includes('Web Application')) {
        return [
            ['Web security scanner?', 'OWASP ZAP', 'Open source'],
            ['Commercial web tool?', 'Burp Suite', 'Popular choice'],
            ['Web proxy use?', 'Intercept requests', 'Modify traffic'],
            ['SQL injection test?', 'Fuzzing', 'Input testing'],
            ['Top web risks?', 'OWASP Top 10', 'Common vulns']
        ];
    }

    if (module.includes('Threat Intelligence')) {
        return [
            ['IOC stands for?', 'Indicator of Compromise', 'Threat evidence'],
            ['Free threat feed?', 'AlienVault OTX', 'Community sharing'],
            ['Threat framework?', 'MITRE ATT&CK', 'TTPs'],
            ['IP reputation?', 'Threat intelligence', 'Known bad IPs'],
            ['Share intel format?', 'STIX', 'Structured format']
        ];
    }

    if (module.includes('Email')) {
        return [
            ['Fraudulent email?', 'Phishing', 'Social engineering'],
            ['Email header info?', 'Source IP', 'Origin'],
            ['Verify sender?', 'SPF', 'Sender Policy'],
            ['Email authentication?', 'DMARC', 'Domain-based'],
            ['Malicious attachment?', 'Malware', 'Infected file']
        ];
    }

    if (module.includes('Social Engineering')) {
        return [
            ['Manipulate people?', 'Social Engineering', 'Human hacking'],
            ['Fake identity?', 'Pretexting', 'Made-up scenario'],
            ['Urgent request?', 'Urgency', 'Pressure tactic'],
            ['Authority exploit?', 'Impersonation', 'Pose as boss'],
            ['Defense method?', 'Awareness training', 'Education']
        ];
    }

    if (module.includes('Virtualization')) {
        return [
            ['Virtual machine software?', 'VirtualBox', 'Free hypervisor'],
            ['Commercial VM tool?', 'VMware', 'Enterprise option'],
            ['VM snapshot benefit?', 'Restore state', 'Undo changes'],
            ['Isolated network?', 'Host-only', 'No internet'],
            ['VM disk format?', 'VMDK', 'Virtual disk']
        ];
    }

    // Default questions
    return [
        ['Core concept?', 'Security operations', 'SOC work'],
        ['Best practice?', 'Documentation', 'Record findings'],
        ['Analysis tool?', 'SIEM', 'Log platform'],
        ['Incident response?', 'Investigate', 'Analyze threat'],
        ['Continuous improvement?', 'Training', 'Learn more']
    ];
}

createPath2Batch();
