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

async function completeModule2AndSimplifyQuestions() {
    try {
        console.log('Starting comprehensive updates...\n');

        // First, delete all existing questions to replace with simplified ones
        console.log('Clearing existing questions...');
        await db.query('DELETE FROM lesson_questions');
        console.log('✓ Cleared old questions\n');

        // ===== MODULE 1: SIMPLIFIED QUESTIONS =====
        console.log('Adding simplified Module 1 questions...');

        // Task 1: Networking
        const task1Questions = [
            [1, 'HTTPS port number?', '443', 1, 'Secure web traffic uses port...', 0],
            [1, 'DNS full form?', 'Domain Name System', 2, 'Translates domain names', 0],
            [1, 'MITM attack name?', 'Man-in-the-Middle', 3, 'Intercepting communications', 0],
            [1, 'LAN full form?', 'Local Area Network', 4, 'Home/office network', 0]
        ];
        for (const q of task1Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 2: OSI Model  
        const task2Questions = [
            [2, 'How many OSI layers?', '7', 1, 'Seven layers total', 0],
            [2, 'Physical layer number?', '1', 2, 'Bottom layer', 0],
            [2, 'Application layer number?', '7', 3, 'Top layer', 0],
            [2, 'Transport layer protocols?', 'TCP and UDP', 4, 'Two main protocols', 0],
            [2, 'Which layer routes packets?', 'Network', 5, 'Layer 3', 0]
        ];
        for (const q of task2Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 3: Career Paths
        const task3Questions = [
            [3, 'SOC Analyst main task?', 'Monitor security alerts', 1, 'First line of defense', 0],
            [3, 'Entry-level certification?', 'Security+', 2, 'CompTIA cert', 0],
            [3, 'Pentester salary range?', '80k-120k', 3, 'Ethical hacker pay', 0],
            [3, 'CISO stands for?', 'Security Officer', 4, 'Chief Information...', 0]
        ];
        for (const q of task3Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 4: Quiz
        const task4Questions = [
            [4, 'What protects systems?', 'Cybersecurity', 1, 'Digital protection', 0],
            [4, 'Traffic flood attack?', 'DDoS', 2, 'Denial of Service', 0],
            [4, 'Secure web protocol?', 'HTTPS', 3, 'Port 443', 0],
            [4, 'CIA first word?', 'Confidentiality', 4, 'C in CIA triad', 0],
            [4, 'Malicious software?', 'Malware', 5, 'Harmful programs', 0],
            [4, 'Network monitoring tool?', 'IDS', 6, 'Intrusion Detection...', 0]
        ];
        for (const q of task4Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 5: Lab Setup
        const task5Questions = [
            [5, 'Beginner virtualization platform?', 'VirtualBox', 1, 'Free and easy', 0],
            [5, 'Security testing Linux?', 'Kali Linux', 2, 'Pre-loaded tools', 0],
            [5, 'Practice vulnerability system?', 'Metasploitable', 3, 'Intentionally vulnerable', 0],
            [5, 'Isolated network mode?', 'Host-Only', 4, 'No internet access', 0],
            [5, 'Packet analyzer tool?', 'Wireshark', 5, 'Network traffic viewer', 0]
        ];
        for (const q of task5Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        console.log('✓ Added simplified Module 1 questions\n');

        // ===== MODULE 2: SIMPLIFIED QUESTIONS =====
        console.log('Adding simplified Module 2 questions...');

        // Task 6: File Navigation
        const task6Questions = [
            [6, 'Show current directory?', 'pwd', 1, 'Print working directory', 0],
            [6, 'Change directory command?', 'cd', 2, 'Navigate folders', 0],
            [6, 'List files command?', 'ls', 3, 'View directory contents', 0],
            [6, 'Root directory symbol?', '/', 4, 'Top of filesystem', 0],
            [6, 'Home directory shortcut?', '~', 5, 'Tilde symbol', 0]
        ];
        for (const q of task6Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 7: File Manipulation
        const task7Questions = [
            [7, 'Create empty file?', 'touch', 1, 'Make new file', 0],
            [7, 'Copy files command?', 'cp', 2, 'Duplicate files', 0],
            [7, 'Rename file command?', 'mv', 3, 'Move or rename', 0],
            [7, 'Delete file command?', 'rm', 4, 'Remove files', 0],
            [7, 'View file contents?', 'cat', 5, 'Display text', 0]
        ];
        for (const q of task7Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 8: Permissions
        const task8Questions = [
            [8, 'Read permission letter?', 'r', 1, 'View files', 0],
            [8, 'Write permission letter?', 'w', 2, 'Modify files', 0],
            [8, 'Execute permission letter?', 'x', 3, 'Run files', 0],
            [8, 'Full permissions number?', '777', 4, 'Read+write+execute for all', 0],
            [8, 'Change permissions command?', 'chmod', 5, 'Modify file access', 0]
        ];
        for (const q of task8Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 9: Finding Files
        const task9Questions = [
            [9, 'Search files command?', 'find', 1, 'Locate files', 0],
            [9, 'Fast search command?', 'locate', 2, 'Database search', 0],
            [9, 'Find by name flag?', '-name', 3, 'Specify filename', 0],
            [9, 'Find by size flag?', '-size', 4, 'File size filter', 0],
            [9, 'Find by type flag?', '-type', 5, 'File or directory', 0]
        ];
        for (const q of task9Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        console.log('✓ Added simplified Module 2 questions (6-9)\n');

        // ===== ADD MISSING MODULE 2 LESSONS (10-13) =====
        console.log('Adding remaining Module 2 lesson content...');

        // Task 10: grep
        const task10Content = `# Text Manipulation with grep

\`grep\` is one of the most powerful tools for searching text in files. Essential for SOC analysts reviewing logs and hunting for IOCs.

## What is grep?

**g**lobally search for a **r**egular **e**xpression and **p**rint matching lines

## Basic Usage

\`\`\`bash
grep "error" logfile.txt
grep "failed" /var/log/auth.log
\`\`\`

## Common Options

\`\`\`bash
grep -i "error" file.txt      # Case-insensitive
grep -n "failed" file.txt     # Show line numbers
grep -v "success" file.txt    # Invert (show non-matching)
grep -r "malware" /var/log/   # Recursive search
grep -c "error" file.txt      # Count matches
\`\`\`

## Security Examples

**Find failed logins:**
\`\`\`bash
grep "Failed password" /var/log/auth.log
\`\`\`

**Search for IP address:**
\`\`\`bash
grep "192.168.1.100" access.log
\`\`\`

**Find suspicious commands:**
\`\`\`bash
grep -i "wget\\|curl" bash_history
\`\`\``;

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

        const task10Questions = [
            [10, 'Text search command?', 'grep', 1, 'Search file contents', 0],
            [10, 'Case-insensitive flag?', '-i', 2, 'Ignore case', 0],
            [10, 'Show line numbers?', '-n', 3, 'Number lines', 0],
            [10, 'Recursive search flag?', '-r', 4, 'Search directories', 0],
            [10, 'Count matches flag?', '-c', 5, 'Total occurrences', 0]
        ];
        for (const q of task10Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 11: Process Management
        const task11Content = `# Linux Process Management

Managing processes is crucial for identifying malicious activity, troubleshooting performance, and maintaining system security.

## Viewing Processes

### \`ps\` - Process Status
\`\`\`bash
ps aux                # All processes
ps -ef                # Full listing
ps | grep apache      # Find specific process
\`\`\`

### \`top\` - Real-time Processes
\`\`\`bash
top                   # Interactive view
htop                  # Enhanced version
\`\`\`

## Managing Processes

### \`kill\` - Terminate Process
\`\`\`bash
kill 1234             # Graceful shutdown (SIGTERM)
kill -9 1234          # Force kill (SIGKILL)
killall firefox       # Kill by name
\`\`\`

### Background Jobs
\`\`\`bash
command &             # Run in background
jobs                  # List background jobs
fg                    # Bring to foreground
bg                    # Resume in background
\`\`\`

## Security Use Cases

**Find suspicious processes:**
\`\`\`bash
ps aux | grep -i suspicious
\`\`\`

**Monitor resource usage:**
\`\`\`bash
top -u hacker
\`\`\`

**Kill malicious process:**
\`\`\`bash
kill -9 <pid>
\`\`\``;

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

        const task11Questions = [
            [11, 'List processes command?', 'ps', 1, 'Process status', 0],
            [11, 'Real-time monitor?', 'top', 2, 'Live process view', 0],
            [11, 'Kill process command?', 'kill', 3, 'Terminate process', 0],
            [11, 'Force kill signal?', '-9', 4, 'SIGKILL', 0],
            [11, 'Background job symbol?', '&', 5, 'Run in background', 0]
        ];
        for (const q of task11Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 12: Package Management
        const task12Content = `# Package Management

Installing and managing software is a daily task. Learn the package managers for different Linux distributions.

## Debian/Ubuntu (apt)

\`\`\`bash
sudo apt update                # Update package list
sudo apt upgrade               # Upgrade packages
sudo apt install nmap          # Install package
sudo apt remove nmap           # Remove package
sudo apt search wireshark      # Search packages
\`\`\`

## RedHat/CentOS (yum/dnf)

\`\`\`bash
sudo yum install nmap
sudo yum remove nmap
sudo yum update
\`\`\`

## Security Tools Installation

\`\`\`bash
sudo apt install nmap
sudo apt install wireshark
sudo apt install netcat
sudo apt install tcpdump
\`\`\`

## Best Practices

- Always update before installing
- Only install from trusted repositories
- Keep system updated for security patches
- Remove unused packages`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)', [12, task12Content, 'markdown', 6]);

        const task12Questions = [
            [12, 'Ubuntu package manager?', 'apt', 1, 'Debian-based systems', 0],
            [12, 'Update package list?', 'apt update', 2, 'Refresh repositories', 0],
            [12, 'Install package command?', 'apt install', 3, 'Add new software', 0],
            [12, 'Remove package command?', 'apt remove', 4, 'Delete software', 0],
            [12, 'RedHat package manager?', 'yum', 5, 'RHEL/CentOS', 0]
        ];
        for (const q of task12Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        // Task 13: Linux Challenge
        const task13Content = `# Linux Command Line Challenge

Time to test everything you've learned! This challenge combines navigation, file manipulation, permissions, and text processing.

## Challenge Objectives

You'll practice:
- File system navigation
- Creating and modifying files
- Setting permissions
- Searching for content
- Process management

## Quick Reference

**Navigation:**
- \`pwd\`, \`cd\`, \`ls\`

**Files:**
- \`touch\`, \`cp\`, \`mv\`, \`rm\`, \`cat\`

**Permissions:**
- \`chmod\`, \`chown\`

**Search:**
- \`find\`, \`grep\`

**Processes:**
- \`ps\`, \`top\`, \`kill\`

**Packages:**
- \`apt\` commands

Ready to apply your skills!`;

        await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)', [13, task13Content, 'markdown', 5]);

        const task13Questions = [
            [13, 'Create directory command?', 'mkdir', 1, 'Make folder', 0],
            [13, 'View last log lines?', 'tail', 2, 'End of file', 0],
            [13, 'Search text in files?', 'grep', 3, 'Pattern matching', 0],
            [13, 'List all processes?', 'ps aux', 4, 'View running programs', 0],
            [13, 'Change file owner?', 'chown', 5, 'Ownership modification', 0]
        ];
        for (const q of task13Questions) {
            await db.query('INSERT INTO lesson_questions (task_id, question_text, correct_answer, question_order, hint, case_sensitive) VALUES (?, ?, ?, ?, ?, ?)', q);
        }

        console.log('✓ Added lessons for tasks 10-13\n');
        console.log('\n✅ ALL UPDATES COMPLETE!');
        console.log('- Simplified all questions to max 3 words');
        console.log('- Added helpful hints to all questions');
        console.log('- Completed Module 2 lessons (tasks 6-13)');
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

completeModule2AndSimplifyQuestions();
