const db = require('../db');
const { evaluateInvestigation } = require('../utils/aiService');
const { sendInvestigationGradedEmail } = require('../utils/emailService');
const { advanceOperationProgress } = require('../controllers/operationController');

const runAutoGrader = async () => {
    console.log('[AutoGrader] Checking for pending investigations...');
    try {
        // 1. Find investigations that are 'submitted' (remove 5 min delay for instant feedback during testing)
        // const fiveMinutesAgo = new Date(Date.now() - 5 * 60 * 1000); 

        const pendingInvestigations = await db.query(`
            SELECT i.*, a.title as alert_title, a.severity, a.details, a.real_world_example, a.raw_log, u.email as user_email, u.name as user_name
            FROM investigations i
            JOIN alerts a ON i.alert_id = a.id
            JOIN users u ON i.user_id = u.id
            WHERE i.status = 'submitted' 
            AND (i.ai_evaluation_scheduled_at <= NOW() OR i.ai_evaluation_scheduled_at IS NULL) 
        `);
        // Removed: AND i.updated_at < ?

        console.log(`[AutoGrader] Found ${pendingInvestigations.rows.length} investigations ready for grading.`);

        if (pendingInvestigations.rows.length === 0) return;

        // 2. Fetch AI Settings
        const settingsResult = await db.query('SELECT * FROM system_settings WHERE category = "ai_integration"');
        const aiSettings = {};
        settingsResult.rows.forEach(row => {
            try {
                aiSettings[row.key] = JSON.parse(row.value);
            } catch (e) {
                aiSettings[row.key] = row.value;
            }
        });

        if (aiSettings.ai_evaluation_enabled !== 'true' && aiSettings.ai_evaluation_enabled !== true) {
            console.log('[AutoGrader] AI evaluation is disabled in settings. Skipping.');
            return;
        }

        // 3. Process each investigation
        for (const investigation of pendingInvestigations.rows) {
            console.log(`[AutoGrader] Grading investigation ${investigation.id} for user ${investigation.user_name}...`);

            try {
                // Parse the user's summary
                let summary = investigation.executive_summary;
                if (typeof summary === 'string') {
                    try {
                        summary = JSON.parse(summary);
                    } catch (e) {
                        console.error(`[AutoGrader] Failed to parse summary for investigation ${investigation.id}`, e);
                        continue; // Skip valid JSON parsing errors
                    }
                }

                const ticketData = {
                    title: investigation.alert_title,
                    severity: investigation.severity,
                    details: investigation.details,
                    raw_log: investigation.raw_log, // NEW: Pass raw_log for direct AI analysis
                    // REMOVED: answer_key - AI will analyze raw_log directly
                    verdict: summary.summary?.verdict || summary.verdict,
                    analysis: (summary.summary?.analysis || summary.analysis || '') +
                        (summary.analysis_answers?.action_taken ? `\nActions Taken: ${Array.isArray(summary.analysis_answers.action_taken) ? summary.analysis_answers.action_taken.join(', ') : summary.analysis_answers.action_taken}` : '') +
                        (summary.analysis_answers?.attack_category ? `\nAttack Category: ${summary.analysis_answers.attack_category}` : ''),
                    artifacts: summary.artifacts || summary.analysis_answers?.artifacts || '',
                    summary: summary.summary?.conclusion || summary.executive_summary || '',
                    conclusion: summary.summary?.conclusion || summary.conclusion
                };

                let finalGrade = null;
                let finalFeedback = null;
                let finalAiSummary = null;

                // Check if already graded (e.g. by Playbook)
                if (investigation.grade !== null && investigation.grade !== undefined) {
                    console.log(`[AutoGrader] Investigation ${investigation.id} already has grade ${investigation.grade}. Skipping AI evaluation.`);
                    finalGrade = investigation.grade;
                    finalFeedback = "Graded via Playbook Answer Key.";
                    finalAiSummary = { grade: finalGrade, feedback: finalFeedback };
                } else {
                    // AI Evaluation
                    const aiResult = await evaluateInvestigation(ticketData, aiSettings);
                    if (!aiResult) {
                        console.error(`[AutoGrader] AI returned null for investigation ${investigation.id}`);
                        continue;
                    }
                    finalGrade = aiResult.grade;
                    finalFeedback = aiResult.feedback;
                    finalAiSummary = aiResult.ai_summary;
                }

                // Determine Status
                const needsApproval = (aiSettings.ai_admin_approval === 'true' || aiSettings.ai_admin_approval === true) && !investigation.grade; // Skip approval if playbook graded? Or respect? User wants flow. Let's assume Playbook is trusted.
                const newStatus = needsApproval ? 'submitted' : 'graded';

                await db.query(
                    `UPDATE investigations 
                     SET grade = ?, 
                         feedback = ?, 
                         ai_summary = ?, 
                         status = ?, 
                         updated_at = NOW() 
                     WHERE id = ?`,
                    [
                        finalGrade,
                        finalFeedback,
                        JSON.stringify(finalAiSummary),
                        newStatus,
                        investigation.id
                    ]
                );

                // If graded, CLOSE the alert
                if (newStatus === 'graded') {
                    await db.query(
                        `UPDATE alerts 
                         SET status = 'Closed', 
                             analyst_notes = CONCAT(COALESCE(analyst_notes, ''), ?) 
                         WHERE id = ?`,
                        [`\n[${new Date().toLocaleString()}] [SYSTEM] Investigation Closed. Grade: ${finalGrade}. Summary: ${summary.summary?.conclusion || 'Completed.'}`, investigation.alert_id]
                    );
                }

                console.log(`[AutoGrader] Successfully finalized investigation ${investigation.id}. Grade: ${finalGrade}`);

                // Advance operation progress if this alert is part of an operation
                await advanceOperationProgress(investigation.user_id, investigation.alert_id, finalGrade);

                // Send Email
                if (investigation.user_email) {
                    await sendInvestigationGradedEmail(
                        investigation.user_email,
                        investigation.user_name,
                        investigation.alert_title,
                        finalGrade,
                        finalFeedback
                    );
                }

            } catch (err) {
                console.error(`[AutoGrader] Error processing investigation ${investigation.id}:`, err);
            }
        }

    } catch (error) {
        console.error('[AutoGrader] Critical Error:', error);
    }
};

module.exports = { runAutoGrader };
