// =============================================
// sp-agent.js — Phoenix Agent Mode
// =============================================
import { state } from './sp-state.js';
import { GEMINI_BASE, TOOL_DECLARATIONS } from './sp-config.js';
import { PERSONAS } from './sp-personas.js';
import { executeToolCall } from './sp-tools.js';
import { addBotMessage, playAudioAlert } from './sp-ui.js';

let _agentSteps, _agentProgress, _btnLaunchAgent, _agentGoal;
let _btnAgent, _agentPanel, _btnStopAgent, _settingsPanel, _backpackPanel;

export function initAgent(els) {
    _agentSteps = els.agentSteps;
    _agentProgress = els.agentProgress;
    _btnLaunchAgent = els.btnLaunchAgent;
    _agentGoal = els.agentGoal;
    _btnAgent = els.btnAgent;
    _agentPanel = els.agentPanel;
    _btnStopAgent = els.btnStopAgent;
    _settingsPanel = els.settingsPanel;
    _backpackPanel = els.backpackPanel;

    if (_btnAgent) {
        _btnAgent.addEventListener('click', () => {
            if (_settingsPanel) _settingsPanel.classList.add('hidden');
            if (_backpackPanel) _backpackPanel.classList.add('hidden');
            const personasPanel = document.getElementById('personas-panel');
            if (personasPanel) personasPanel.classList.add('hidden');
            const providersPanel = document.getElementById('providers-panel');
            if (providersPanel) providersPanel.classList.add('hidden');
            const isHidden = _agentPanel.classList.toggle('hidden');
            
            document.querySelectorAll('.sidebar-btn').forEach(btn => btn.classList.remove('active'));
            if (isHidden) {
                const btnChat = document.getElementById('btn-sidebar-chat');
                if (btnChat) btnChat.classList.add('active');
            } else {
                _btnAgent.classList.add('active');
            }
        });
    }
    if (_btnLaunchAgent) {
        _btnLaunchAgent.addEventListener('click', () => {
            const goal = _agentGoal.value.trim();
            if (!goal) { _agentGoal.focus(); return; }
            _agentPanel.classList.add('hidden');
            runAgent(goal);
        });
    }
    if (_btnStopAgent) {
        _btnStopAgent.addEventListener('click', () => {
            state.agentRunning = false;
            try { chrome.action.setBadgeText({ text: '' }); } catch { }
            agentLog('⛔ Stopped by user.');
        });
    }
}

export function agentLog(msg) {
    if (!_agentSteps) return;
    const line = document.createElement('div');
    line.style.cssText = 'padding:2px 0;border-bottom:1px solid #e2e8f0;color:#374151;';

    const timeSpan = document.createElement('span');
    timeSpan.style.color = '#93c5fd';
    timeSpan.textContent = `[${new Date().toLocaleTimeString()}] `;
    line.appendChild(timeSpan);

    const textNode = document.createTextNode(msg);
    line.appendChild(textNode);

    _agentSteps.appendChild(line);
    _agentSteps.scrollTop = _agentSteps.scrollHeight;
}

export async function runAgent(goal) {
    if (!goal.trim() || (!state.config.apiKey && !state.config.baseUrl)) return;
    state.agentRunning = true;
    try { chrome.action.setBadgeText({ text: '⚡' }); chrome.action.setBadgeBackgroundColor({ color: '#f59e0b' }); } catch { }

    _agentProgress.style.display = 'block';
    _agentSteps.innerHTML = '';
    _btnLaunchAgent.textContent = '⏳ Agent Running...';
    _btnLaunchAgent.disabled = true;

    agentLog(`🚀 Mission received: "${goal.substring(0, 80)}..."`);
    agentLog('🧠 Initializing autonomous loop...');

    const agentHistory = [];
    agentHistory.push({ role: 'user', parts: [{ text: `[PHOENIX AGENT MISSION]
You are running in full autonomous agent mode. Your manager is Pidgey Assist.
Your mission: "${goal}"

Run autonomously. Use all available tools sequentially. Search → screenshot → scrape → act.

BLINDNESS PROTOCOL (CRITICAL!): Never complain that you are "blind" or that "Puppeteer cannot see". If you need to see the current UI, you MUST call the 'take_screenshot' tool to gain Eagle-Eye Vision. Always take a screenshot before attempting complex clicks.
SWARM PROTOCOL: If you are asked to use multiple agents or a "Swarm", you MUST call the 'delegate_task' tool to spawn specialized sub-agents.
CRITICAL DATA VERIFICATION: Modern sites load dynamically. If a scrape returns "Loading...", wait or retry.
ESCALATION: If you absolutely cannot complete the task, do NOT hallucinate success. Report failure to Pidgey.
REPORT GENERATION: You MUST save the final results using 'create_libreoffice_document', 'generate_image', OR 'save_to_backpack'. Do NOT just output text in chat and halt. You MUST save the output to the backpack before you end the loop!` }] });

    let loopCount = 0;
    const maxLoops = 250;
    try {
        const allLocal = await chrome.storage.local.get(null);
        const backpackFiles = {};
        for (const k in allLocal) {
            if (k.startsWith('_file_')) {
                const content = allLocal[k] || '';
                backpackFiles[k.replace('_file_', '')] = `[Size: ${content.length} chars] Preview: ${content.substring(0, 150).replace(/\n/g, ' ')}...`;
            }
        }
        const backpackCtx = Object.keys(backpackFiles).length ? `\n\n[📦 PIDGEY BACKPACK SYSTEM INDEX:\n${JSON.stringify(backpackFiles)}\nNote: This is just a file index. If you need the full content of any file, use the 'read_from_backpack' tool!]\n` : '';

        while (state.agentRunning && loopCount < maxLoops) {
            loopCount++;
            agentLog(`🔄 Loop ${loopCount}/${maxLoops} — calling Gemini...`);
            let url = state.config.baseUrl || GEMINI_BASE;
            if (url && !url.startsWith('http') && !url.includes('generative')) url = 'http://' + url;
            if (state.config.baseUrl && !state.config.baseUrl.includes('generative')) {
                if (!url.endsWith('/chat/completions')) { if (!url.endsWith('/')) url += '/'; url += 'chat/completions'; }
            } else {
                url = `${url}/${state.config.model}:generateContent`;
            }
            const personaConfig = PERSONAS[state.activePersona] || PERSONAS.assist;
            const currentPrompt = personaConfig.prompt + `\nCurrent Model Context: ${state.config.model} (Acknowledge this if asked about your version or model).` + backpackCtx;
            const allowedTools = personaConfig.tools ? TOOL_DECLARATIONS.filter(t => personaConfig.tools.includes(t.name)) : TOOL_DECLARATIONS;
            const res = await fetch(url, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'x-goog-api-key': state.config.apiKey || 'ollama' },
                body: JSON.stringify({
                    system_instruction: { parts: [{ text: currentPrompt }] },
                    contents: agentHistory,
                    generationConfig: { temperature: 0.5, topP: 0.9, maxOutputTokens: 4096 },
                    tools: [{ functionDeclarations: allowedTools }]
                })
            });
            if (!res.ok) { agentLog(`❌ API error ${res.status}`); break; }
            const data = await res.json();
            const candidate = data.candidates?.[0];
            if (!candidate) { agentLog('❌ No response from Gemini'); break; }

            const parts = candidate.content?.parts || [];
            agentHistory.push({ role: 'model', parts });
            const textParts = parts.filter(p => p.text).map(p => p.text);
            const fnCalls = parts.filter(p => p.functionCall);

            if (textParts.length) agentLog(`💬 Pidgey: "${textParts.join(' ').substring(0, 120).replace(/\n/g, ' ')}..."`);

            if (!fnCalls.length) {
                agentLog('✅ Agent mission complete!');
                playAudioAlert('chirp');
                addBotMessage(`🤖 **Phoenix Agent Report:**\n\n${textParts.join('\n') || 'Mission complete — check your Backpack!'}`);
                try { chrome.action.setBadgeText({ text: '✓' }); chrome.action.setBadgeBackgroundColor({ color: '#22c55e' }); setTimeout(() => { if (!state.agentRunning) chrome.action.setBadgeText({ text: '' }); }, 4000); } catch { }
                break;
            }

            const responses = [];
            for (const fc of fnCalls) {
                agentLog(`🔧 Tool: ${fc.functionCall.name}`);
                const result = await executeToolCall(fc.functionCall).catch(err => ({
                    display: `Tool "${fc.functionCall.name}" failed: ${err.message}`,
                    result: `Error executing ${fc.functionCall.name}: ${err.message}`
                }));
                const resultText = (typeof result === 'string') ? result
                    : (result?.result ?? result?.display ?? JSON.stringify(result));
                agentLog(`   ↪ Result: ${String(resultText).substring(0, 100).replace(/\n/g, ' ')}...`);
                responses.push({ functionResponse: { name: fc.functionCall.name, response: { result: resultText } } });
            }
            agentHistory.push({ role: 'function', parts: responses });
        }
        if (loopCount >= maxLoops) {
            agentLog('⚠️ Max loops reached — mission ended.');
            try { chrome.action.setBadgeText({ text: '!' }); chrome.action.setBadgeBackgroundColor({ color: '#ef4444' }); setTimeout(() => { if (!state.agentRunning) chrome.action.setBadgeText({ text: '' }); }, 4000); } catch { }
        }
    } catch (err) {
        agentLog(`❌ Agent error: ${err.message}`);
        try { chrome.action.setBadgeText({ text: '!' }); chrome.action.setBadgeBackgroundColor({ color: '#ef4444' }); setTimeout(() => { if (!state.agentRunning) chrome.action.setBadgeText({ text: '' }); }, 4000); } catch { }
    }

    state.agentRunning = false;
    _btnLaunchAgent.textContent = '🚀 Launch Agent';
    _btnLaunchAgent.disabled = false;
    agentLog('🛑 Agent stopped.');
}
