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

async function createWindowsCliLessons() {
    try {
        console.log('🚀 Creating Refined Windows CLI Lessons (Module 11)\n');

        // 1. Rename Module 11
        await db.query(`UPDATE modules SET title = 'Windows Command Line', description = 'Master essential Windows commands: Navigation, Files, Networking, and Processes.', estimated_hours = 5 WHERE id = 11`);

        // 2. Define Tasks (Renamed to match specific challenges)
        const tasks = [
            { id: 48, title: 'Navigating Directories' },
            { id: 49, title: 'Reading Files' },
            { id: 50, title: 'Host Identity' },
            { id: 51, title: 'IP Configuration' },
            { id: 52, title: 'Terminating Processes' }
        ];

        // Ensure tasks exist and are active
        for (const t of tasks) {
            await db.query(`INSERT INTO tasks (id, module_id, title, is_active, display_order) VALUES (?, 11, ?, 1, ?) ON DUPLICATE KEY UPDATE title = VALUES(title), is_active=1`, [t.id, t.title, t.id - 47]);
        }

        // 3. Content Mapping (Aligned with linuxChallenges.js missions)
        const lessons = {
            48: {
                title: 'Navigating Directories',
                content: `# Mission: Navigation

In this lesson, you will learn how to look around and move between folders in the Windows Command Prompt.

## 1. dir (Directory)
The \`dir\` command lists all files and subfolders in your current location.
*   **Usage**: \`dir\`

## 2. cd (Change Directory)
The \`cd\` command moves you into a new folder.
*   **Usage**: \`cd FolderName\`
*   **Go Back**: \`cd ..\` moves you up one level.

## Your Challenge
1.  Run \`dir\` to see the available folders.
2.  You will see a **"Documents"** folder.
3.  Run \`cd Documents\` to enter it.`,
                questions: [
                    ['Which command lists files?', 'dir', 'Directory', ['ls', 'list', 'dir', 'show']],
                    ['How do you enter the "Documents" folder?', 'cd Documents', 'Change Directory', ['dir Documents', 'cd Documents', 'enter Documents', 'go Documents']],
                    ['What does "cd .." do?', 'Go back one level', 'Parent directory', ['Deletes folder', 'Go back one level', 'Go to root', 'Nothing']]
                ]
            },
            49: {
                title: 'Reading Files',
                content: `# Mission: Reading Files

In this lesson, you will learn how to read the contents of a text file directly in the terminal.

## 1. type
The \`type\` command displays the text inside a file. It is the Windows equivalent of \`cat\` in Linux.
*   **Usage**: \`type filename.txt\`

## Your Challenge
There is a file named **secret.txt** in your current directory.
1.  Read its content to find the secret password.
2.  **Command**: \`type secret.txt\``,
                questions: [
                    ['Which command reads a file content?', 'type', 'Type out', ['read', 'cat', 'type', 'open']],
                    ['If you want to read "note.txt", what do you type?', 'type note.txt', 'Command + Arg', ['read note.txt', 'type note.txt', 'cat note.txt', 'open note.txt']],
                    ['Is "cat" a standard Windows command?', 'No', 'type is used', ['Yes', 'No', 'Maybe', 'Only in PowerShell']]
                ]
            },
            50: {
                title: 'Host Identity',
                content: `# Mission: Who are we?

In cyber reconnaissance, the first step is often identifying the machine you have compromised.

## 1. hostname
Displays the name of the computer on the network.
*   **Usage**: \`hostname\`

## 2. whoami
Displays the currently logged-in user (Domain\\User).
*   **Usage**: \`whoami\`

## Your Challenge
We need to gather intelligence about this machine.
1.  Run \`hostname\` to find the computer name.
2.  Run \`whoami\` to find the user name.`,
                questions: [
                    ['Which command shows the computer name?', 'hostname', 'Host', ['name', 'hostname', 'computername', 'id']],
                    ['Which command shows the current user?', 'whoami', 'Identity', ['user', 'me', 'whoami', 'id']],
                    ['Why is "whoami" important?', 'To check permissions', 'Privilege level', ['To check time', 'To check IP', 'To check permissions', 'To list files']]
                ]
            },
            51: {
                title: 'IP Configuration',
                content: `# Mission: Network Config

You need to know your IP address to understand your place in the network.

## 1. ipconfig
Displays the basic IP configuration for all adapters.
*   **IPv4 Address**: Your local IP (e.g., 192.168.1.105).
*   **Subnet Mask**: Defines the network size.
*   **Default Gateway**: The router you use to access the internet.

## Your Challenge
Run \`ipconfig\` to retrieve the network details of this machine.`,
                questions: [
                    ['Which command shows IP details on Windows?', 'ipconfig', 'IP Config', ['ifconfig', 'ipconfig', 'ip a', 'net config']],
                    ['What does Default Gateway usually represent?', 'The Router', 'Exit point', ['The PC', 'The Router', 'The Server', 'The DNS']],
                    ['What is a common local IP starting with?', '192.168', 'Private range', ['8.8.8', '192.168', '1.1.1', '255.255']]
                ]
            },
            52: {
                title: 'Terminating Processes',
                content: `# Mission: Process Killer

Sometimes malware runs as a background process. You need to find it and kill it.

## 1. tasklist
Lists all running processes. Look for the **PID** (Process ID), a unique number for each process.

## 2. taskkill
Stops a process. You often use the \`/PID\` switch to specify the exact ID.
*   **Usage**: \`taskkill /PID 1234\`
*   **/F**: Forces the termination (sometimes required).

## Your Challenge
A malicious **notepad.exe** is running with **PID 1337**.
1.  Terminate it immediately.
2.  **Command**: \`taskkill /PID 1337\``,
                questions: [
                    ['Which command lists running processes?', 'tasklist', 'List tasks', ['ps', 'tasklist', 'proclist', 'top']],
                    ['What does PID stand for?', 'Process ID', 'Identifier', ['Program ID', 'Process ID', 'Personal ID', 'Path ID']],
                    ['Which switch is used to kill by PID?', '/PID', 'Switch', ['-p', '/PID', '-id', '--pid']]
                ]
            }
        };

        let totalCreated = 0;
        
        // Iterate through the lesson keys (IDs)
        for (const [idStr, lesson] of Object.entries(lessons)) {
            const taskId = parseInt(idStr);
            console.log(`Processing Task ${taskId}: ${lesson.title}`);

            // Clean up existing content
            await db.query('DELETE FROM lesson_content WHERE task_id = ?', [taskId]);
            await db.query('DELETE FROM lesson_questions WHERE task_id = ?', [taskId]);

            // Insert Content
            await db.query('INSERT INTO lesson_content (task_id, content, content_type, reading_time_minutes) VALUES (?, ?, ?, ?)',
                [taskId, lesson.content, 'markdown', 5]);

            // Insert Questions (3 max)
            for (let j = 0; j < Math.min(lesson.questions.length, 3); 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]);
            }
            totalCreated++;
        }

        console.log(`\n✅ Refined Windows CLI Module (11) Created! (${totalCreated} lessons)\n`);
        process.exit(0);
    } catch (error) {
        console.error('Error:', error);
        process.exit(1);
    }
}

createWindowsCliLessons();
