import * as vscode from 'vscode';
import { ZAIChatModelProvider } from './provider';
import { ApiKeyManager } from './apiKeyManager';

let provider: ZAIChatModelProvider | undefined;

export async function activate(context: vscode.ExtensionContext) {
    console.log('Z.AI Language Models extension is now active');

    // Initialize API key manager
    const apiKeyManager = new ApiKeyManager(context);

    // Create and register the provider
    provider = new ZAIChatModelProvider(apiKeyManager);
    const providerDisposable = vscode.lm.registerLanguageModelChatProvider('zai', provider);
    context.subscriptions.push(providerDisposable);

    // Register commands
    const manageApiKeyCommand = vscode.commands.registerCommand('zai.manageApiKey', async () => {
        const apiKey = await vscode.window.showInputBox({
            prompt: 'Enter your Z.AI API Key',
            password: true,
            placeHolder: 'sk-...',
            validateInput: (value) => {
                if (!value || value.trim().length === 0) {
                    return 'API key cannot be empty';
                }
                return null;
            }
        });

        if (apiKey) {
            await apiKeyManager.setApiKey(apiKey);
            vscode.window.showInformationMessage('Z.AI API key saved successfully');
            
            // Refresh the provider to pick up the new key
            if (provider) {
                await provider.refresh();
            }
        }
    });

    const clearApiKeyCommand = vscode.commands.registerCommand('zai.clearApiKey', async () => {
        const confirm = await vscode.window.showWarningMessage(
            'Are you sure you want to clear your Z.AI API key?',
            'Yes',
            'No'
        );

        if (confirm === 'Yes') {
            await apiKeyManager.clearApiKey();
            vscode.window.showInformationMessage('Z.AI API key cleared');
            
            // Refresh the provider
            if (provider) {
                await provider.refresh();
            }
        }
    });

    context.subscriptions.push(manageApiKeyCommand, clearApiKeyCommand);

    // Show welcome message on first activation
    const hasSeenWelcome = context.globalState.get<boolean>('zai.hasSeenWelcome', false);
    if (!hasSeenWelcome) {
        const setupAction = 'Setup API Key';
        const result = await vscode.window.showInformationMessage(
            'Welcome to Z.AI Language Models! Set up your API key to get started.',
            setupAction,
            'Later'
        );

        if (result === setupAction) {
            await vscode.commands.executeCommand('zai.manageApiKey');
        }
        
        await context.globalState.update('zai.hasSeenWelcome', true);
    }
}

export function deactivate() {
    console.log('Z.AI Language Models extension is now deactivated');
}
