const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '../../.env') });
const db = require('../db');

async function seedAcademyAlerts() {
    console.log("🚀 Starting Academy Alert Seeding...");

    try {
        // 1. Fetch all tasks for the Alert Investigation path (ID 9) with their content
        const rows = await db.query(`
            SELECT T.id as task_id, T.title, LC.content 
            FROM tasks T 
            JOIN lesson_content LC ON T.id = LC.task_id 
            JOIN modules M ON T.module_id = M.id 
            WHERE M.learning_path_id = 9
            ORDER BY T.id ASC
        `);

        if (rows.length === 0 && rows.rows) {
             // Handle mysql2 vs postgres style
             // My previous tools showed .rows so assuming .rows or array direct
             // Actually mysql2 usually returns [rows, fields] in promise mode? 
             // Wrapper in db.js: returns result (which might be the array)
        }
        
        // Normalize rows (db.query wrapper returns different things depending on driver)
        const tasks = rows.rows || rows; 
        console.log(`Found ${tasks.length} lessons to process.`);

        for (const task of tasks) {
            console.log(`\nProcessing Task [${task.task_id}] ${task.title}...`);

            // 2. Extract Raw Log from Markdown
            // Regex to find content between ```json ... ``` or ```text ... ```
            // We want the content inside the first code block that isn't the "SQL" or "Answer" block if multiple
            // Usually the log is the first code block in my lessons.
            const codeBlockRegex = /```(?:json|xml|text|splunk|http|vba)?\n([\s\S]*?)\n```/;
            const match = task.content.match(codeBlockRegex);

            let rawLog = null;
            if (match) {
                rawLog = match[1];
                console.log(`   found raw log (${rawLog.length} chars)`);
            } else {
                console.warn(`   ⚠️ NO RAW LOG FOUND in markdown. Skipping alert creation.`);
                continue;
            }

            // 3. Create Alert
            // We'll generate a realistic description based on the title
            const alertTitle = `Simulation: ${task.title}`;
            const description = `This is a training simulation for the lesson '${task.title}'. Investigate the attached raw log.`;
            
            // Cleanup: Delete existing academy alert for this task if any (to prevent duplicates on re-run)
            // But we don't have a direct link back from alert to task except via the task column we just added.
            // We can check if task.alert_id is already set.
            
            // Insert new alert
            const insertResult = await db.query(`
                INSERT INTO alerts (
                    title, 
                    severity, 
                    source, 
                    status, 
                    details, 
                    alert_type, 
                    raw_log, 
                    created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
            `, [
                alertTitle,
                'Medium',      // Default severity
                'Academy',     // Hidden source
                'new',
                description,
                'Simulation',
                rawLog
            ]);

            const alertId = insertResult.insertId || insertResult.rows[0].id;
            console.log(`   ✅ Created Alert ID: ${alertId}`);

            // 4. Update Task
            await db.query(`UPDATE tasks SET alert_id = ? WHERE id = ?`, [alertId, task.task_id]);
            console.log(`   🔗 Linked Alert ${alertId} to Task ${task.task_id}`);
        }

        console.log("\n✨ Academy Alerts Seeded Successfully!");
        process.exit(0);

    } catch (error) {
        console.error("❌ Seeding Failed:", error);
        process.exit(1);
    }
}

seedAcademyAlerts();
