/**
 * Alert Automation Service
 * Handles the generation and assignment of automated daily threat briefings
 */

const db = require('../db');
const blogAutomationService = require('./blogAutomationService');
const aiService = require('../utils/aiService');
const assignmentService = require('./assignmentService');
const { broadcastPushNotification } = require('../utils/notificationService');

/**
 * Run Daily Threat Briefing
 * Fetches latest news, generates alerts, and assigns to active users.
 */
async function runDailyBriefing(options = {}) {
    const force = options.force === true;
    console.log('--- STARTING DAILY THREAT BRIEFING ---', force ? '[FORCE MODE]' : '');
    const timestamp = new Date().toISOString();
    
    try {
        // 1. Check if enabled
        const enabledResult = await db.query(
            "SELECT value FROM system_settings WHERE `key` = 'daily_ai_briefing_enabled'"
        );
        let enabled = enabledResult.rows.length > 0 ? enabledResult.rows[0].value : 'false';
        if (typeof enabled === 'string') enabled = enabled.replace(/^"|"$/g, '').toLowerCase();

        if (enabled !== 'true' && !force) {
            console.log('[DailyBriefing] Feature disabled in settings. Skipping.');
            return { success: false, message: 'Feature disabled' };
        }

        // 2. Prevent duplicate runs today (Unless forced)
        const today = new Date().toISOString().substring(0, 10);
        const lastRunResult = await db.query(
            "SELECT value FROM system_settings WHERE `key` = 'daily_briefing_last_run'"
        );
        if (!force && lastRunResult.rows.length > 0 && lastRunResult.rows[0].value === today) {
            console.log(`[DailyBriefing] Already ran today (${today}). Skipping.`);
            return { success: false, message: 'Already ran today' };
        }

        // Mark as run immediately to prevent race conditions
        await db.query(
            "INSERT INTO system_settings (`key`, value, category) VALUES (?, ?, 'ai_integration') ON DUPLICATE KEY UPDATE value = ?",
            ['daily_briefing_last_run', today, today]
        );

        // 3. Fetch AI Settings
        const settingsResult = await db.query(
            "SELECT \`key\`, value FROM system_settings WHERE category IN ('ai_integration', 'automation')"
        );
        const settings = {};
        settingsResult.rows.forEach(row => {
            try { settings[row.key] = JSON.parse(row.value); }
            catch (e) { settings[row.key] = row.value; }
        });

        // Cleanup API Key
        if (settings.ai_api_key && typeof settings.ai_api_key === 'string') {
            settings.ai_api_key = settings.ai_api_key.replace(/^"|"$/g, '').trim();
        }

        const count = parseInt(settings.daily_ai_briefing_count) || 2;
        const level = parseInt(settings.daily_ai_briefing_level) || 5;
        const pathCode = settings.daily_ai_briefing_path || 'AUTO';
        
        console.log(`[DailyBriefing] Config: Count=${count}, Level=${level}, Path=${pathCode}`);

        // 4. Fetch Trending News Candidates
        const newsItems = await blogAutomationService.getTrendingCandidates(count + 5); // Fetch extra for selection
        if (!newsItems || newsItems.length === 0) {
            console.log('[DailyBriefing] No trending news items found. Skipping.');
            return { success: false, message: 'No news found' };
        }

        // Sort by score and take top N
        const topNews = newsItems
            .sort((a, b) => (b.score || 0) - (a.score || 0))
            .slice(0, count);

        console.log(`[DailyBriefing] Selected ${topNews.length} news items for transformation.`);

        const generatedAlertIds = [];

        // 5. Generate Alerts for each news item
        for (const news of topNews) {
            try {
                console.log(`[DailyBriefing] Generating alert for: ${news.title}`);
                const alertData = await aiService.generateAlertFromNews(
                    news, 
                    settings.ai_api_key, 
                    settings.ai_provider || 'openai',
                    {
                        level: level,
                        path_code: pathCode
                    }
                );

                if (!alertData) {
                    console.error(`[DailyBriefing] Failed to generate alert for: ${news.title}`);
                    continue;
                }

                // Insert into Database with full metadata alignment
                const result = await db.query(
                    'INSERT INTO alerts (title, severity, status, source, details, alert_type, mitre_technique, real_world_example, raw_log, playbook_solution, is_ai_generated, sector_code, difficulty, min_level, path_code, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?, ?, NOW())',
                    [
                        alertData.title,
                        alertData.severity || 'Medium',
                        'New',
                        alertData.source || 'Threat Intelligence',
                        alertData.details,
                        alertData.alert_type,
                        alertData.mitre_technique,
                        1, 
                        JSON.stringify(alertData.raw_log),
                        JSON.stringify(alertData.playbook_solution),
                        alertData.sector_code || null,
                        alertData.difficulty || 'Intermediate',
                        alertData.min_level || level,
                        alertData.path_code || (pathCode === 'AUTO' ? null : pathCode)
                    ]
                );

                generatedAlertIds.push(result.insertId);
                console.log(`[DailyBriefing] Created Alert ID: ${result.insertId}`);
            } catch (alertError) {
                console.error(`[DailyBriefing] Error processing news item "${news.title}":`, alertError.message);
            }
        }

        if (generatedAlertIds.length === 0) {
            return { success: false, message: 'Failed to generate any alerts' };
        }

        // 6. Proactive Assignment to Active Users
        console.log(`[DailyBriefing] Assigning ${generatedAlertIds.length} new alerts to active users.`);
        
        // Target all verified non-admin users
        const activeUsersResult = await db.query(
            "SELECT id FROM users WHERE is_verified = 1 AND role != 'admin'"
        );
        const activeUsers = activeUsersResult.rows;

        for (const user of activeUsers) {
            for (const alertId of generatedAlertIds) {
                try {
                    await db.query(
                        `INSERT IGNORE INTO user_alert_assignments 
                         (user_id, alert_id, assigned_date, completed, is_replay, xp_earned)
                         VALUES (?, ?, ?, 0, 0, 0)`,
                        [user.id, alertId, today]
                    );
                } catch (assignErr) {
                    // Skip duplicates
                }
            }
        }

        // 7. Notify via Push if any generated and setting allows
        const sendPush = settings.daily_ai_briefing_send_push !== 'false' && settings.daily_ai_briefing_send_push !== false;
        
        if (generatedAlertIds.length > 0 && sendPush) {
            broadcastPushNotification(
                'Daily Threat Briefing Ready 🛰️',
                `${generatedAlertIds.length} new real-world alerts have been added to your dashboard.`,
                { screen: 'DailyQueue' }
            ).catch(e => console.error('Push Broadcast Error:', e));
        }

        console.log(`--- DAILY THREAT BRIEFING COMPLETE: ${generatedAlertIds.length} ALERTS ---`);
        return { success: true, count: generatedAlertIds.length, ids: generatedAlertIds };

    } catch (error) {
        console.error('[DailyBriefing] Fatal Error:', error);
        return { success: false, error: error.message };
    }
}

module.exports = {
    runDailyBriefing
};
