const db = require('../db');
const { evaluateInvestigation } = require('./aiService');
const badgeService = require('../services/badgeService');
const xpService = require('./xpService');
// Helper to get AI Key
const getAIKey = async () => {
    try {
        const result = await db.query("SELECT value FROM system_settings WHERE `key` = 'ai_api_key'");
        return result.rows[0]?.value || process.env.OPENAI_API_KEY;
    } catch (e) {
        return process.env.OPENAI_API_KEY;
    }
};

// Helper to get AI settings
const getAISettings = async () => {
    try {
        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;
            }
        });
        return aiSettings;
    } catch (e) {
        console.error('Error fetching AI settings:', e);
        return {};
    }
};

/**
 * Process a single investigation for AI grading
 * @param {Object} investigation - Investigation DB Record
 * @param {Object} alert - Alert DB Record
 */
const gradeInvestigation = async (investigation, alert) => {
    try {
        console.log(`[GradingService] Starting grading for investigation ${investigation.id}...`);
        
        const aiSettings = await getAISettings();
        
        // Check if AI evaluation is enabled
        if (aiSettings.ai_evaluation_enabled !== 'true' && aiSettings.ai_evaluation_enabled !== true) {
            console.log('[GradingService] AI evaluation disabled. Applying default grade.');
            await db.query(
                `UPDATE investigations SET status = 'graded', grade = 75, feedback = 'Automated grading completed (AI Disabled).', updated_at = NOW() WHERE id = ?`,
                [investigation.id]
            );
            return;
        }

        // Prepare Ticket Data
        let summaryObj = {};
        try {
            summaryObj = typeof investigation.executive_summary === 'string' 
                ? JSON.parse(investigation.executive_summary) 
                : investigation.executive_summary || {};
        } catch (e) { console.error("Error parsing summary JSON", e); }

        const ticketData = {
            title: alert.title || alert.alert_title,
            severity: alert.severity,
            details: alert.details,
            raw_log: alert.raw_log,
            verdict: summaryObj.verdict || 'Unknown',
            analysis: (summaryObj.analysis_answers?.action_taken ? `Actions Taken: ${Array.isArray(summaryObj.analysis_answers.action_taken) ? summaryObj.analysis_answers.action_taken.join(', ') : summaryObj.analysis_answers.action_taken}` : '') +
                (summaryObj.analysis_answers?.attack_category ? `\nAttack Category: ${summaryObj.analysis_answers.attack_category}` : ''),
            artifacts: summaryObj.artifacts || '',
            summary: summaryObj.executive_summary || '',
            conclusion: summaryObj.analysis_answers?.conclusion || ''
        };

        const aiResult = await evaluateInvestigation(ticketData, aiSettings);

        if (aiResult) {
            await db.query(
                `UPDATE investigations 
                 SET grade = ?, feedback = ?, ai_summary = ?, status = 'graded', updated_at = NOW() 
                 WHERE id = ?`,
                [aiResult.grade, aiResult.feedback, JSON.stringify(aiResult.ai_summary), investigation.id]
            );
            console.log(`[GradingService] Success! Investigation ${investigation.id} graded: ${aiResult.grade}`);
            
            // Award XP if passing grade
            if (aiResult.grade >= 60) {
                const xpResult = await xpService.awardXP(investigation.user_id, aiResult.grade);
                console.log(`[GradingService] Awarded ${aiResult.grade} XP to user ${investigation.user_id}. New Level: ${xpResult?.level}`);
            }

            // Check badges and streak (in case they weren't checked before)
            // Note: Streak is usually updated on submission, but badges might depend on grade
            await badgeService.checkPerformanceBadges(investigation.user_id, { ...investigation, grade: aiResult.grade });

        } else {
            console.log(`[GradingService] AI returned null result. Applying fallback.`);
            await db.query(
                `UPDATE investigations SET status = 'graded', grade = 70, feedback = 'Grading completed (Fallback).', updated_at = NOW() WHERE id = ?`,
                [investigation.id]
            );
        }

    } catch (error) {
        console.error(`[GradingService] Error grading investigation ${investigation.id}:`, error);
        // Fallback on error to ensure it doesn't stay stuck
        await db.query(
            `UPDATE investigations SET grade = 65, feedback = 'Investigation processed. Please review manually if needed.', status = 'graded', updated_at = NOW() WHERE id = ?`,
            [investigation.id]
        );
    }
};

/**
 * Find and process any investigations stuck in 'submitted' state
 */
const processPendingSubmissions = async () => {
    try {
        console.log('[GradingService] Checking for pending submissions...');
        
        // Find investigations that are 'submitted' and older than 1 minute (to give immediate processors time)
        // OR just process anything 'submitted' (idempotency is handled by status check logic in caller usually, but here we query by status)
        const pendingResult = await db.query(`
            SELECT i.*, a.title, a.severity, a.details, a.raw_log 
            FROM investigations i
            JOIN alerts a ON i.alert_id = a.id
            WHERE i.status = 'submitted'
            LIMIT 50
        `);

        if (pendingResult.rows.length === 0) {
            return;
        }

        console.log(`[GradingService] Found ${pendingResult.rows.length} pending investigations.`);

        for (const record of pendingResult.rows) {
            await gradeInvestigation(record, record); // record contains joined alert fields
        }
        
    } catch (error) {
        console.error('[GradingService] Error processing pending submissions:', error);
    }
};

/**
 * V2 Deterministic Grading Logic
 */


module.exports = {
    gradeInvestigation,
    processPendingSubmissions
};
