import * as vscode from 'vscode';
import { buildApiUrl, logInfo, logError } from '../utils';

/**
 * Astra 첫 실행 시 자동 셋업 마법사 — LM Studio/Ollama URL 자동 감지 + 사용자 확인.
 * extension.ts 의 `activate()` 가 처음 호출될 때 한 번 실행. 이미 사용자가 URL 을
 * 설정해 둔 환경에서는 즉시 skip.
 */
export async function runInitialSetup(context: vscode.ExtensionContext) {
    // 이미 사용자가 URL을 설정했다면 자동 감지를 스킵
    const existingUrl = vscode.workspace.getConfiguration('g1nation').get<string>('ollamaUrl');
    if (existingUrl && existingUrl.trim()) {
        context.globalState.update('setupComplete', true);
        logInfo('Initial setup skipped: ollamaUrl already configured.', { existingUrl });
        return;
    }

    try {
        let engineName = '';
        let modelName = '';
        
        try {
            const res = await fetch(buildApiUrl('http://127.0.0.1:1234', 'lmstudio', 'models'), { signal: AbortSignal.timeout(2000) });
            const data = await res.json() as any;
            if (data?.data?.length > 0) {
                engineName = 'LM Studio';
                modelName = data.data[0].id;
                await vscode.workspace.getConfiguration('g1nation').update('ollamaUrl', 'http://127.0.0.1:1234', vscode.ConfigurationTarget.Global);
                await vscode.workspace.getConfiguration('g1nation').update('defaultModel', modelName, vscode.ConfigurationTarget.Global);
                logInfo('Initial setup detected LM Studio.', { modelName });
            }
        } catch (err) {
            logInfo('Initial setup could not reach LM Studio.', err);
        }

        if (!engineName) {
            try {
                const res = await fetch('http://127.0.0.1:11434/api/tags', { signal: AbortSignal.timeout(2000) });
                const data = await res.json() as any;
                if (data?.models?.length > 0) {
                    engineName = 'Ollama';
                    modelName = data.models[0].name;
                    await vscode.workspace.getConfiguration('g1nation').update('ollamaUrl', 'http://127.0.0.1:11434', vscode.ConfigurationTarget.Global);
                    await vscode.workspace.getConfiguration('g1nation').update('defaultModel', modelName, vscode.ConfigurationTarget.Global);
                    logInfo('Initial setup detected Ollama.', { modelName });
                }
            } catch (err) {
                logInfo('Initial setup could not reach Ollama.', err);
            }
        }

        context.globalState.update('setupComplete', true);
        if (engineName) {
            vscode.window.showInformationMessage(`Setup Complete: ${engineName} detected with model ${modelName}`);
        }
    } catch (e) {
        logError('Initial setup failed.', e);
        context.globalState.update('setupComplete', true);
    }
}
