// backend/src/scripts/improve_lessons.js
// Script to regenerate all lesson content with improved formatting and user-friendly structure

const mysql = require('mysql2/promise');
require('dotenv').config({ path: require('path').join(__dirname, '../../.env') });

const dbConfig = {
    host: process.env.DB_HOST || 'localhost',
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'infosecl_platform'
};

// Enhanced lesson content templates by module category
const lessonTemplates = {
    // For core concept lessons
    concept: (title, topic) => `
## 🎯 Learning Objective

Understand **${title}** and its role in modern cybersecurity operations.

---

## 📖 Core Concept

${topic} is a foundational element of security.

### What is it?
${topic} involves:
- **Identification**: Recognizing patterns
- **Analysis**: Understanding impact
- **Mitigation**: Reducing risk

### Why it Matters
Without ${topic}, organizations cannot effectively defend against threats.

---

## ⚡ Quick Facts

- **Criticality**: High
- **Frequency**: Daily
- **Impact**: Operational Security

---

## 🛠️ Analyst Workflow

1. **Monitor**: Watch for indicators
2. **Analyze**: Verify context
3. **Escalate**: If confirmed threat

---

## 📝 Summary

Mastering **${title}** is essential for Level 1 SOC analysts.
`,

    // For tool-based lessons
    tool: (title, toolName) => `
## 🎯 Learning Objective

Learn to use **${toolName}** for effective security analysis.

---

## 📖 Tool Overview

**${toolName}** is a standard industry tool used for:
- 🔍 Deep inspection
- 📊 Data analysis
- 🛡️ Threat hunting

---

## 💻 Command Reference

### Basic Syntax
\`\`\`bash
${toolName.toLowerCase()} [options] <target>
\`\`\`

### Top 3 Options
| Flag | Purpose |
|------|---------|
| \`-v\` | Verbose mode |
| \`-h\` | Help menu |
| \`-o\` | Output file |

---

## 💡 Pro Tip
> Always verify tool output with a second source when possible.

---

## 📝 Summary

Practice with **${toolName}** in the lab to build muscle memory.
`,

    // For attack scenarios
    attack: (title, attackType) => `
## 🎯 Learning Objective

Recognize and defend against **${attackType}** attacks.

---

## ⚠️ Threat Profile

**${attackType}** is a common attack vector where adversaries attempt to:
- 🔓 Gain unauthorized access
- 🕵️ Steal sensitive data
- 🛑 Disrupt services

---

## 🔍 Detection Indicators

Look for these signs in your SIEM:
1. **Unusual Traffic**: Spikes in volume
2. **Failed Logins**: Multiple attempts
3. **New Accounts**: Created outside business hours

---

## 🛡️ Response Actions

If detected:
1. **Isolate** the affected host
2. **Block** the source IP
3. **Reset** compromised credentials

---

## 📝 Summary

Early detection of **${attackType}** minimizes organizational impact.
`,

    // For defensive strategies
    defense: (title, strategy) => `
## 🎯 Learning Objective

Implement **${strategy}** to harden security posture.

---

## 🛡️ Strategy Overview

**${strategy}** provides a robust layer of defense by:
- Reducing attack surface
- Increasing attack cost
- Improving visibility

---

## 📋 Implementation Checklist

- [ ] Audit current controls
- [ ] Deploy updated policies
- [ ] Verify logging is active
- [ ] Test effectiveness regularily

---

## 💡 Best Practice
> Security is a process, not a product. Continuous improvement is key.

---

## 📝 Summary

**${strategy}** is a vital component of a defense-in-depth architecture.
`
};

// Generate improved content based on task/module context
function generateImprovedContent(task, moduleName) {
    const title = task.title;
    const lowerTitle = title.toLowerCase();
    const lowerModule = (moduleName || '').toLowerCase();

    // Select strictly based on keywords, default to concept
    if (lowerTitle.includes('tool') || lowerTitle.includes('grep') || lowerTitle.includes('wireshark') || lowerTitle.includes('nmap') || lowerTitle.includes('command')) {
        return lessonTemplates.tool(title, title.split(' ')[0]);
    } else if (lowerTitle.includes('attack') || lowerTitle.includes('phishing') || lowerTitle.includes('malware') || lowerTitle.includes('injection')) {
        return lessonTemplates.attack(title, title);
    } else if (lowerTitle.includes('defense') || lowerTitle.includes('hardening') || lowerTitle.includes('firewall') || lowerTitle.includes('protection')) {
        return lessonTemplates.defense(title, title);
    } else {
        return lessonTemplates.concept(title, title);
    }
}

// Generate improved questions as MCQs with 4 options
function generateImprovedQuestions(taskId, taskTitle, moduleTitle) {
    const questions = [];

    // Pool of questions with distractors
    const questionPool = [
        {
            text: "What is the primary goal of this concept?",
            answer: "Risk reduction",
            distractors: ["Cost increase", "Data deletion", "System slowdown"],
            hint: "Lowers danger"
        },
        {
            text: "Which team handles these incidents?",
            answer: "SOC team",
            distractors: ["HR Department", "Sales Team", "Marketing"],
            hint: "Security Operations"
        },
        {
            text: "What is the priority level?",
            answer: "High priority",
            distractors: ["Low priority", "No priority", "Optional"],
            hint: "Urgency level"
        },
        {
            text: "What is the first step in response?",
            answer: "Detection",
            distractors: ["Panic", "Shutdown", "Ignoring"],
            hint: "Finding it"
        },
        {
            text: "What tool category is this?",
            answer: "Security tool",
            distractors: ["Office tool", "Game engine", "Music player"],
            hint: "Software type"
        },
        {
            text: "What is the main output?",
            answer: "Log data",
            distractors: ["Music files", "Video streams", "Printer ink"],
            hint: "Event records"
        },
        {
            text: "Who is the primary adversary?",
            answer: "Threat actor",
            distractors: ["System admin", "Regular user", "Manager"],
            hint: "Malicious user"
        },
        {
            text: "What is the defensive goal?",
            answer: "Protection",
            distractors: ["Exposure", "Sharing", "Deleting"],
            hint: "Safety"
        },
        {
            text: "What should you analyze first?",
            answer: "Context",
            distractors: ["Lunch menu", "Weather", "Sports scores"],
            hint: "The situation"
        },
        {
            text: "When to escalate?",
            answer: "Confirmed threat",
            distractors: ["False alarm", "Minor bug", "User login"],
            hint: "Real danger"
        }
    ];

    // Select exactly 3 random unique questions
    const selected = questionPool.sort(() => 0.5 - Math.random()).slice(0, 3);

    selected.forEach((q, index) => {
        // Create options array (correct + distractors) and shuffle
        const options = [q.answer, ...q.distractors].sort(() => 0.5 - Math.random());

        questions.push({
            task_id: taskId,
            question_text: q.text,
            correct_answer: q.answer,
            options: JSON.stringify(options),
            hint: q.hint,
            question_order: index + 1
        });
    });

    return questions;
}

async function improveLessons() {
    let connection;

    try {
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ Connected to database');

        // Get all tasks with their module info
        const [tasks] = await connection.execute(`
            SELECT t.id, t.title, t.module_id, m.title as module_title 
            FROM tasks t 
            JOIN modules m ON t.module_id = m.id 
            ORDER BY t.id
        `);

        console.log(`📚 Found ${tasks.length} tasks to improve`);

        let contentUpdated = 0;
        let questionsUpdated = 0;

        for (const task of tasks) {
            // Generate improved content
            const newContent = generateImprovedContent(task, task.module_title);
            const readingTime = Math.max(3, Math.ceil(newContent.length / 1000));

            // Update lesson content
            await connection.execute(`
                UPDATE lesson_content 
                SET content = ?, reading_time_minutes = ?, updated_at = NOW()
                WHERE task_id = ?
            `, [newContent, readingTime, task.id]);
            contentUpdated++;

            // Delete old questions
            await connection.execute('DELETE FROM lesson_questions WHERE task_id = ?', [task.id]);

            // Insert new improved questions
            const questions = generateImprovedQuestions(task.id, task.title, task.module_title);
            for (const q of questions) {
                await connection.execute(`
                    INSERT INTO lesson_questions (task_id, question_text, correct_answer, options, hint, question_order)
                    VALUES (?, ?, ?, ?, ?, ?)
                `, [q.task_id, q.question_text, q.correct_answer, q.options, q.hint, q.question_order]);
                questionsUpdated++;
            }

            if (contentUpdated % 50 === 0) {
                console.log(`   Progress: ${contentUpdated}/${tasks.length} lessons updated`);
            }
        }

        console.log(`\n✅ Updated ${contentUpdated} lessons`);
        console.log(`✅ Updated ${questionsUpdated} questions`);
        console.log('🎉 Lesson improvement complete!');

    } catch (error) {
        console.error('❌ Error:', error.message);
        throw error;
    } finally {
        if (connection) {
            await connection.end();
        }
    }
}

improveLessons();
