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

// Create Paths 3 & 4 lessons efficiently
async function createPaths34AllLessons() {
    try {
        console.log('🚀 Creating Paths 3 & 4 Lessons - Final Sprint\n');
        let total = 0;

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

        console.log(`Found ${tasks.rows.length} tasks for Paths 3 & 4\n`);

        for (const task of tasks.rows) {
            const content = generateAdvancedContent(task);
            const questions = generateAdvancedQuestions(task);

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

            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 % 20 === 0) console.log(`✓ Created ${total} lessons...`);
        }

        console.log(`\n✅✅✅ PATHS 3 & 4 COMPLETE! Created ${total} lessons\n`);

        const totalLessons = await db.query('SELECT COUNT(*) as count FROM lesson_content');
        const percent = Math.round((totalLessons.rows[0].count / 348) * 100);
        console.log(`🎉 PLATFORM TOTAL: ${totalLessons.rows[0].count}/348 (${percent}%)\n`);

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

function generateAdvancedContent(task) {
    const module = task.module_title;
    const title = task.title;
    const pathId = task.learning_path_id;

    // Path 3: SOC Analyst Level 1 Content
    if (pathId === 3) {
        if (module.includes('SIEM')) {
            return `# ${title}

## SIEM in SOC Operations

Security Information and Event Management (SIEM) is the central platform for security monitoring and incident detection.

## Core Capabilities
- **Log aggregation** from all sources
- **Real-time correlation** of events
- **Automated alerting** on threats
- **Dashboards and visualization**
- **Compliance reporting**

## Key SIEM Platforms
- **Splunk** - Industry leader, powerful SPL
- **Elastic Security** - Open source, scalable
- **IBM QRadar** - Enterprise platform
- **Microsoft Sentinel** - Cloud-native

## SPL (Search Processing Language)
\`\`\`spl
index=security sourcetype=firewall action=blocked
| stats count by src_ip
| where count > 100
| sort -count
\`\`\`

## Detection Use Cases
- Failed login monitoring
- Lateral movement detection
- Data exfiltration patterns
- Malware C2 communication
- Privilege escalation

## SOC Analyst Workflow
1. Monitor dashboards
2. Review triggered alerts
3. Investigate anomalies
4. Correlate events
5. Escalate incidents
6. Document findings

## Best Practices
✅ Tune alerts to reduce noise
✅ Create custom dashboards
✅ Document search queries
✅ Regular rule updates
✅ Baseline normal behavior

SIEM mastery is essential for SOC Level 1 analysts.`;
        }

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

## Endpoint Detection and Response

EDR solutions provide deep endpoint visibility and rapid threat response capabilities.

## Core Functions
- **Continuous monitoring** of endpoints
- **Behavioral analysis** of processes
- **Threat detection** using ML/AI
- **Automated response** actions
- **Forensic investigation** tools

## Popular EDR Solutions
- CrowdStrike Falcon
- SentinelOne
- Microsoft Defender for Endpoint
- Carbon Black

## Detection Capabilities
- Malware execution
- Fileless attacks
- Lateral movement
- Privilege escalation
- Data exfiltration
- Persistence mechanisms

## Response Actions
- Isolate endpoint
- Kill malicious processes
- Quarantine files
- Collect forensic data
- Block network connections

## Investigation Features
- Process tree visualization
- Network connections
- File activity
- Registry modifications
- Memory analysis

## SOC Integration
✓ SIEM connectivity
✓ Automated playbooks
✓ Threat intelligence feeds
✓ Incident response automation

Critical tool for modern SOC operations.`;
        }

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

## Malware Analysis for SOC Analysts

Understanding malware behavior is crucial for effective incident response and threat detection.

## Analysis Levels
### Static Analysis
- Examine without execution
- File hashes (MD5, SHA256)
- Strings extraction
- PE header analysis
- VirusTotal checks

### Dynamic Analysis  
- Execute in sandbox
- Monitor behavior
- Network connections
- File system changes
- Registry modifications

## Common Malware Types
- **Trojans** - Backdoor access
- **Ransomware** - File encryption
- **Spyware** - Data theft
- **Worms** - Self-replicating
- **Rootkits** - Stealth persistence

## Analysis Tools
**Static:**
- VirusTotal
- PEStudio
- Strings command
- YARA rules

**Dynamic:**
- Cuckoo Sandbox
- Any.run
- Joe Sandbox
- REMnux

## Indicators of Compromise
- File hashes
- C2 IP addresses
- Domain names
- File paths
- Registry keys
- Mutex names

## SOC Workflow
1. Receive suspicious file alert
2. Isolate affected system
3. Collect sample safely
4. Perform static analysis
5. Execute in sandbox
6. Document IOCs
7. Create detection rules
8. Update defenses

Essential skill for L1 SOC analysts.`;
        }

        // Default Path 3 content
        return `# ${title}

## SOC Analyst Level 1 Topic

This advanced topic builds on foundational knowledge to develop job-ready SOC analyst skills.

## Professional Context
SOC L1 analysts are the first line of defense, monitoring security systems 24/7 and responding to alerts.

## Key Responsibilities
- Monitor SIEM dashboards
- Triage security alerts
- Investigate incidents
- Document findings
- Escalate complex cases
- Maintain security tools

## Technical Skills Required
- SIEM platform expertise
- Log analysis proficiency
- Network traffic analysis
- Malware identification
- Incident documentation
- Tool operation

## Real-World Application
Apply this knowledge in production SOC environments to detect and respond to actual security incidents.

## Career Progression
Mastering this skill enables advancement to SOC L2 analyst and specialist roles.

## Industry Standards
Follow NIST, SANS, and organizational procedures in all security operations.

This training prepares you for professional SOC analyst positions.`;
    }

    // Path 4: Advanced Content
    if (pathId === 4) {
        if (module.includes('Memory Forensics')) {
            return `# ${title}

## Advanced Memory Forensics

Analyze volatile memory to uncover sophisticated threats that evade traditional detection.

## Why Memory Analysis?
- Detect fileless malware
- Identify rootkits
- Find encrypted data
- Analyze running processes
- Recover artifacts

## Volatility Framework
Industry-standard memory analysis tool

**Key Plugins:**
\`\`\`bash
volatility -f memory.dmp imageinfo
volatility -f memory.dmp pslist
volatility -f memory.dmp  netscan
volatility -f memory.dmp malfind
voltility -f memory.dmp dlllist
\`\`\`

## Analysis Workflow
1. Acquire memory image
2. Identify OS profile
3. List processes
4. Check network connections
5. Scan for injected code
6. Extract suspicious processes
7. Document findings

## Advanced Techniques
- Process injection detection
- Kernel module analysis
- Registry hive extraction
- Password recovery
- Malware unpacking

## Use Cases
✓ APT investigation
✓ Rootkit detection
✓ Incident response
✓ Malware analysis
✓ Data recovery

Essential for advanced threat investigations.`;
        }

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

## Purple Team Collaboration

Bridge offensive and defensive security through collaborative exercises.

## Purple Team Concept
Combination of Red Team (attackers) and Blue Team (defenders) working together to improve security.

## Objectives
- Test detection capabilities
- Improve response procedures
- Validate security controls
- Enhance team collaboration
- Identify gaps

## Exercise Process
1. **Plan**: Define scope and objectives
2. **Execute**: Red team attacks
3. **

Detect**: Blue team monitors
4. **Analyze**: Review detection effectiveness
5. **Improve**: Update defenses
6. **Repeat**: Continuous improvement

## Benefits
✅ Realistic threat scenarios
✅ Improved detection
✅ Better team coordination
✅ Validated security controls
✅ Documented procedures

## Frameworks
- MITRE ATT&CK mapping
- Atomic Red Team tests
- Purple Team exercise templates
- Threat emulation platforms

Advanced security operations methodology.`;
        }

        // Default Path 4 content
        return `# ${title}

## Advanced Security Operations

Expert-level topic for specialized SOC analysts and security professionals.

## Advanced Concepts
Deep dive into sophisticated security operations techniques used by senior analysts and specialists.

## Professional Application
Apply cutting-edge security practices in enterprise and critical infrastructure environments.

## Specialized Skills
- Advanced threat hunting
- Complex incident response
- Security automation
- Threat intelligence analysis
- Red/Blue team operations

## Industry Expertise
Mastery of this topic demonstrates advanced security operations capabilities and readiness for senior roles.

## Career Impact
These skills are highly valued and lead to specialized positions in:
- Threat hunting teams
- Incident response specialists
- Security architects
- Security researchers

## Continuous Learning
Stay current with evolving threats, techniques, and tools through ongoing professional development.

This represents the pinnacle of SOC analyst expertise.`;
    }

    return 'Advanced security operations content.';
}

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

    if (module.includes('SIEM')) {
        return [
            ['SIEM full name?', 'Security Information Event Management', 'Log platform'],
            ['Splunk query language?', 'SPL', 'Search Processing'],
            ['Cloud-native SIEM?', 'Sentinel', 'Microsoft Azure'],
            ['SIEM core function?', 'Correlation', 'Connect events'],
            ['Open source SIEM?', 'Elastic', 'ELK stack']
        ];
    }

    if (module.includes('EDR')) {
        return [
            ['EDR full name?', 'Endpoint Detection Response', 'Endpoint security'],
            ['Isolate compromised system?', 'Network isolation', 'Disconnect'],
            ['Market leader EDR?', 'CrowdStrike', 'Falcon platform'],
            ['EDR detection method?', 'Behavioral analysis', 'Monitor actions'],
            ['Automated response?', 'Playbook', 'SOAR integration']
        ];
    }

    if (module.includes('Malware')) {
        return [
            ['Analysis without execution?', 'Static', 'Safe review'],
            ['Run in controlled environment?', 'Sandbox', 'Isolated'],
            ['File fingerprint?', 'Hash', 'MD5/SHA256'],
            ['Malware database?', 'VirusTotal', 'Online scanner'],
            ['Behavior analysis tool?', 'Cuckoo', 'Sandbox platform']
        ];
    }

    if (module.includes('Forensics')) {
        return [
            ['Memory analysis tool?', 'Volatility', 'RAM examination'],
            ['Volatile data?', 'Memory', 'RAM contents'],
            ['Evidence preservation?', 'Chain of custody', 'Documentation'],
            ['Disk imaging command?', 'dd', 'Bit-by-bit copy'],
            ['Live response?', 'Running system', 'Active collection']
        ];
    }

    if (module.includes('ATT&CK')) {
        return [
            ['Threat framework?', 'MITRE ATT&CK', 'TTPs database'],
            ['Tactic category?', '14', 'Total tactics'],
            ['Initial access tactic?', 'Entry point', 'How they get in'],
            ['Persistence goal?', 'Maintain access', 'Stay hidden'],
            ['Exfiltration purpose?', 'Steal data', 'Data theft']
        ];
    }

    if (module.includes('Threat Hunting')) {
        return [
            ['Proactive searching?', 'Threat hunting', 'Find hidden threats'],
            ['Hypothesis-based hunting?', 'Theory-driven', 'Test assumptions'],
            ['Hunt data source?', 'EDR logs', 'Endpoint data'],
            ['Abnormal behavior?', 'Anomaly', 'Unusual activity'],
            ['Hunt outcome?', 'New detections', 'Improve rules']
        ];
    }

    if (module.includes('Cloud')) {
        return [
            ['AWS security service?', 'GuardDuty', 'Threat detection'],
            ['Azure security center?', 'Defender', 'Cloud protection'],
            ['Shared responsibility?', 'Model', 'Provider and customer'],
            ['Cloud access control?', 'IAM', 'Identity management'],
            ['Container orchestration?', 'Kubernetes', 'K8s platform']
        ];
    }

    if (module.includes('Automation')) {
        return [
            ['Security automation?', 'SOAR', 'Orchestration platform'],
            ['Scripting language?', 'Python', 'Popular choice'],
            ['Automated workflow?', 'Playbook', 'Response steps'],
            ['API integration?', 'REST', 'Web services'],
            ['Automate repetitive?', 'Tasks', 'Efficiency gain']
        ];
    }

    if (module.includes('Purple') || module.includes('Red') || module.includes('Blue')) {
        return [
            ['Offensive team?', 'Red Team', 'Attackers'],
            ['Defensive team?', 'Blue Team', 'Defenders'],
            ['Collaborative team?', 'Purple Team', 'Both sides'],
            ['Attack emulation?', 'Red Team exercise', 'Test defenses'],
            ['Detection validation?', 'Purple Team', 'Verify controls']
        ];
    }

    if (module.includes('Certification') || module.includes('Career')) {
        return [
            ['Entry certification?', 'Security+', 'CompTIA'],
            ['SOC analyst cert?', 'CySA+', 'Cybersecurity Analyst'],
            ['Resume include?', 'Projects', 'Hands-on work'],
            ['Interview prep?', 'Practice', 'Mock questions'],
            ['Continuous learning?', 'Yes', 'Always improving']
        ];
    }

    if (module.includes('Capstone') || module.includes('Simulation')) {
        return [
            ['Realistic scenario?', 'Simulation', 'Practice environment'],
            ['Full investigation?', 'End-to-end', 'Complete process'],
            ['Apply all skills?', 'Integration', 'Everything learned'],
            ['Real-world practice?', 'Hands-on', 'Practical'],
            ['Final assessment?', 'Capstone', 'Comprehensive test']
        ];
    }

    // Default questions
    return [
        ['Advanced topic?', 'Professional', 'Job-ready'],
        ['Expert skill?', 'Specialized', 'Advanced'],
        ['SOC capability?', 'Detection', 'Find threats'],
        ['Incident handling?', 'Response', 'React quickly'],
        ['Career advancement?', 'Continuous learning', 'Keep improving']
    ];
}

createPaths34AllLessons();
