/**
 * Agentic Hub Webview Provider
 * Provides the Agentic Hub panel for managing AI agents + Legion parallel orchestration
 */

const vscode = require('vscode');

class AgenticHubWebviewProvider {
    constructor(context) {
        this._context = context;
        this._view = null;
        this.agents = new Map();
        this.chatProvider = null;
        this._visibilityEmitter = new vscode.EventEmitter();
        this._legionSessions = new Map();
        this._aiService = null;
    }

    onDidChangeVisibility(callback) {
        return this._visibilityEmitter.event(callback);
    }

    setChatProvider(chatProvider) {
        this.chatProvider = chatProvider;
    }

    setAIService(aiService) {
        this._aiService = aiService;
    }

    resolveWebviewView(webviewView, context, token) {
        this._view = webviewView;

        webviewView.onDidChangeVisibility(() => {
            this._visibilityEmitter.fire(webviewView.visible);
        });

        webviewView.webview.options = {
            enableScripts: true,
            localResourceRoots: [this._context.extensionUri]
        };

        webviewView.webview.html = this._getHtmlContent();

        webviewView.webview.onDidReceiveMessage(async (message) => {
            await this._handleMessage(message);
        });
    }

    async _handleMessage(message) {
        switch (message.type) {
            case 'createAgent':
                await this.createAgent(message.data);
                break;
            case 'stopAgent':
                await this.stopAgent(message.data.agentId);
                break;
            case 'sendToAgent':
                await this.sendMessageToAgent(message.data.agentId, message.data.message);
                break;
            case 'legionSpawn':
                await this._legionSpawn(message.data);
                break;
            case 'legionStatus':
                await this._legionGetStatus(message.data.sessionId);
                break;
            case 'legionCollect':
                await this._legionCollect(message.data.sessionId);
                break;
            default:
                console.log('Unknown message type:', message.type);
        }
    }

    async createAgent(config) {
        const agentId = `agent-${Date.now()}`;
        const agent = {
            id: agentId,
            name: config.name || 'New Agent',
            type: config.type || 'general',
            status: 'active',
            createdAt: new Date().toISOString(),
            tasks: []
        };
        this.agents.set(agentId, agent);
        this._updateView();
        return agent;
    }

    async stopAgent(agentId) {
        const agent = this.agents.get(agentId);
        if (agent) {
            agent.status = 'stopped';
            this._updateView();
        }
    }

    async sendMessageToAgent(agentId, message) {
        const agent = this.agents.get(agentId);
        if (agent) {
            agent.tasks.push({
                message,
                timestamp: new Date().toISOString(),
                status: 'pending'
            });
            this._updateView();
        }
    }

    // ── Legion Parallel Orchestration ────────────────────────────────

    async _legionSpawn(data) {
        if (!this._aiService) {
            this._postError('AI Service not initialized');
            return;
        }
        try {
            const tasks = data.tasks || [];
            const result = await this._aiService.legionSpawn(tasks);
            const sessionId = result.session_id;
            this._legionSessions.set(sessionId, { tasks, status: 'running', spawned: new Date().toISOString() });
            this._postMessage({ type: 'legionSpawned', data: { sessionId, taskCount: tasks.length } });
            // Create visual agents for each task
            for (const [i, task] of tasks.entries()) {
                const agentId = `legion-${sessionId}-${i}`;
                this.agents.set(agentId, {
                    id: agentId,
                    name: `Legion #${i + 1}`,
                    type: 'legion',
                    status: 'active',
                    createdAt: new Date().toISOString(),
                    tasks: [{ message: task, timestamp: new Date().toISOString(), status: 'running' }],
                    legionSession: sessionId
                });
            }
            this._updateView();
        } catch (err) {
            this._postError(`Legion spawn failed: ${err.message}`);
        }
    }

    async _legionGetStatus(sessionId) {
        if (!this._aiService) return;
        try {
            const status = await this._aiService.legionStatus(sessionId);
            this._postMessage({ type: 'legionStatus', data: status });
        } catch (err) {
            this._postError(`Legion status failed: ${err.message}`);
        }
    }

    async _legionCollect(sessionId) {
        if (!this._aiService) return;
        try {
            const results = await this._aiService.legionCollect(sessionId);
            // Mark legion agents as completed
            for (const [key, agent] of this.agents) {
                if (agent.legionSession === sessionId) {
                    agent.status = 'completed';
                }
            }
            this._legionSessions.set(sessionId, { ...this._legionSessions.get(sessionId), status: 'completed' });
            this._postMessage({ type: 'legionResults', data: results });
            this._updateView();
        } catch (err) {
            this._postError(`Legion collect failed: ${err.message}`);
        }
    }

    _postMessage(msg) {
        if (this._view) {
            this._view.webview.postMessage(msg);
        }
    }

    _postError(text) {
        this._postMessage({ type: 'error', data: { message: text } });
    }

    _updateView() {
        if (this._view) {
            this._view.webview.postMessage({
                type: 'agentsUpdated',
                data: Array.from(this.agents.values())
            });
        }
    }

    _getHtmlContent() {
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Agentic Hub</title>
    <style>
        body {
            font-family: var(--vscode-font-family);
            background: var(--vscode-editor-background);
            color: var(--vscode-editor-foreground);
            padding: 16px;
            margin: 0;
        }
        .header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 16px;
        }
        .header h2 {
            margin: 0;
            font-size: 14px;
        }
        .section-title {
            font-size: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            margin: 12px 0 6px;
            color: var(--vscode-descriptionForeground);
        }
        .agent-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        .agent-card {
            background: var(--vscode-input-background);
            border: 1px solid var(--vscode-input-border);
            border-radius: 4px;
            padding: 12px;
        }
        .agent-name {
            font-weight: 600;
            margin-bottom: 4px;
        }
        .agent-status {
            font-size: 12px;
            color: var(--vscode-descriptionForeground);
        }
        .status-active { color: #4EC9B0; }
        .status-stopped { color: #F48771; }
        .status-completed { color: #89D185; }
        .status-running { color: #CCA700; }
        .empty-state {
            text-align: center;
            padding: 32px;
            color: var(--vscode-descriptionForeground);
        }
        .legion-input {
            width: 100%;
            padding: 6px 8px;
            margin: 8px 0;
            background: var(--vscode-input-background);
            color: var(--vscode-input-foreground);
            border: 1px solid var(--vscode-input-border);
            border-radius: 3px;
            font-size: 12px;
        }
        .btn {
            padding: 4px 12px;
            font-size: 12px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
            background: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
        }
        .btn:hover { background: var(--vscode-button-hoverBackground); }
        .badge {
            display: inline-block;
            padding: 1px 6px;
            border-radius: 8px;
            font-size: 10px;
            font-weight: 600;
        }
        .badge-legion { background: #3b3b4f; color: #CCA700; }
    </style>
</head>
<body>
    <div class="header">
        <span>🤖</span>
        <h2>Agentic Hub</h2>
    </div>

    <div class="section-title">⚔️ Legion — Parallel Tasks</div>
    <textarea id="legionInput" class="legion-input" rows="3" placeholder="Enter tasks separated by | (pipe)&#10;e.g. Lint src/ | Write tests | Update docs"></textarea>
    <button class="btn" onclick="spawnLegion()">⚔️ Spawn Legion</button>

    <div class="section-title" style="margin-top:16px">Agents</div>
    <div id="agentList" class="agent-list">
        <div class="empty-state">
            <p>No active agents</p>
            <p style="font-size: 12px;">Use Build, Agent, or Operator mode to spawn agents</p>
        </div>
    </div>

    <div id="legionResults" style="display:none; margin-top:12px">
        <div class="section-title">Legion Results</div>
        <pre id="legionResultsContent" style="font-size:11px; white-space:pre-wrap; background:var(--vscode-input-background); padding:8px; border-radius:4px;"></pre>
    </div>

    <script>
        const vscode = acquireVsCodeApi();

        function spawnLegion() {
            const input = document.getElementById('legionInput').value;
            const tasks = input.split('|').map(t => t.trim()).filter(Boolean);
            if (tasks.length === 0) return;
            vscode.postMessage({ type: 'legionSpawn', data: { tasks } });
            document.getElementById('legionInput').value = '';
        }

        window.addEventListener('message', event => {
            const msg = event.data;
            if (msg.type === 'agentsUpdated') updateAgentList(msg.data);
            if (msg.type === 'legionSpawned') {
                const el = document.getElementById('legionResultsContent');
                el.textContent = 'Session ' + msg.data.sessionId + ' — ' + msg.data.taskCount + ' agents spawned...';
                document.getElementById('legionResults').style.display = 'block';
            }
            if (msg.type === 'legionResults') {
                const el = document.getElementById('legionResultsContent');
                el.textContent = JSON.stringify(msg.data, null, 2);
                document.getElementById('legionResults').style.display = 'block';
            }
            if (msg.type === 'error') {
                const el = document.getElementById('legionResultsContent');
                el.textContent = '❌ ' + (msg.data?.message || 'Unknown error');
                document.getElementById('legionResults').style.display = 'block';
            }
        });

        function updateAgentList(agents) {
            const container = document.getElementById('agentList');
            if (agents.length === 0) {
                container.innerHTML = '<div class="empty-state"><p>No active agents</p></div>';
                return;
            }
            container.innerHTML = agents.map(agent => {
                const badge = agent.type === 'legion' ? '<span class="badge badge-legion">LEGION</span> ' : '';
                return '<div class="agent-card">' +
                    '<div class="agent-name">' + badge + agent.name + '</div>' +
                    '<div class="agent-status status-' + agent.status + '">' + agent.status + '</div>' +
                '</div>';
            }).join('');
        }
    </script>
</body>
</html>`;
    }
}

module.exports = { AgenticHubWebviewProvider };
