const axios = require('axios');
const { validateAndFixAlerts } = require('../utils/aiService');

/**
 * Generate a single custom alert based on user input
 * Ensures consistency between raw_log and playbook_solution for auto-grading
 * 
 * @param {Object} alertData - User provided alert data
 * @param {string} alertData.title
 * @param {string} alertData.severity
 * @param {string} alertData.alert_type
 * @param {string} alertData.details - The scenario description
 * @param {string} alertData.difficulty
 * @param {string} apiKey - OpenAI API Key
 */
const generateCustomAlert = async (alertData, apiKey) => {
    const { title, severity, alert_type, details, difficulty } = alertData;

    if (!apiKey) {
        throw new Error("API Key is required for AI alert generation");
    }

    console.log(`[AlertGenerator] Generating custom alert: ${title}`);

    const titleInstruction = title && title.trim() 
        ? `- Title: ${title} (USE THIS EXACT TITLE)`
        : `- Title: GENERATE a concise, descriptive alert title based on the scenario (e.g., "Suspicious PDF Attachment from External Domain", "Cobalt Strike Beacon Detection")`;

    const prompt = `
    Generate a DETAILED cybersecurity alert (v2 format) based on the following specific scenario.
    
    INPUT PARAMETERS (MUST RESPECT):
    ${titleInstruction}
    - Severity: ${severity}
    - Alert Type: ${alert_type}
    - Difficulty: ${difficulty || 'Intermediate'} (Scale: Novice, Beginner, Intermediate, Advanced, Expert)
    - Scenario Description: ${details}
    
    REQUIREMENTS:
    1. "title": ${title && title.trim() ? `Use exactly "${title}"` : 'Create a professional, descriptive alert title (max 60 chars) that summarizes the threat. Examples: "Phishing: Fake HR Portal Credential Harvest", "Malware: Emotet Dropper via Macro Document"'}
    
    2. "raw_log": Generate a REALISTIC JSON log entry that matches the scenario.
       - Include timestamps (use current time), IPs, users, filenames, hashes, etc.
       - Must look like a real log from a ${alert_type} source (e.g., firewall, EDR, email gateway).
    
    3. "playbook_solution":
       - "playbook_version": 2
       - "artifacts": Array of artifacts found in raw_log.
         - "id": "artifact_x"
         - "type": "ip|hash|domain|url|email|filename|username|payload|command"
         - "value": MUST MATCH EXACTLY with raw_log value
         - "is_critical": boolean (true for IoCs)
         - "osint_result": { source, verdict (malicious/suspicious/clean/internal), details }
       - "expected_actions": ["isolate_host", "block_ip", "block_hash", "reset_credentials", "collect_forensics", "escalate", "close_alert"]
       - "expected_verdict": "True Positive" (unless scenario implies otherwise)
       - "analysis_notes": Brief explanation of the findings.
    
    CRITICAL RULES:
    1. All artifact values in 'playbook_solution' MUST exist in 'raw_log' exactly.
    2. Ensure the 'raw_log' supports the 'severity' (e.g., Critical alerts should have clear indicators of compromise).
    3. Determine 'mitre_technique' based on the scenario.
    
    OUTPUT: Valid JSON object for a single alert.
    {
       "title": "Descriptive Alert Title Here",
       "severity": "${severity}",
       "source": "Recommended Source",
       "details": "${details}",
       "alert_type": "${alert_type}",
       "mitre_technique": "Txxxx",
       "real_world_example": 1,
       "raw_log": { ... },
       "playbook_solution": { ... }
    }
    `;

    try {
        const response = await axios.post('https://api.openai.com/v1/chat/completions', {
            model: "gpt-4o",
            messages: [
                { role: "system", content: "You are a senior SOC content engineer. Generate realistic, consistent alert data. Output valid JSON only." },
                { role: "user", content: prompt }
            ],
            response_format: { type: "json_object" },
            temperature: 0.7
        }, {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            timeout: 60000
        });

        let alert = JSON.parse(response.data.choices[0].message.content);

        // Ensure playbook version is 2
        if (!alert.playbook_solution) alert.playbook_solution = {};
        alert.playbook_solution.playbook_version = 2;

        // Validation & Fixes
        const validation = validateAndFixAlerts([alert]);
        if (validation.validAlerts.length > 0) {
            return validation.validAlerts[0];
        } else {
            console.warn("[AlertGenerator] Validation failed, returning original AI response");
            return alert;
        }

    } catch (error) {
        console.error("OpenAI Alert Generation Error:", error.message);
        throw new Error("Failed to generate alert content");
    }
};

module.exports = {
    generateCustomAlert
};
