"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ZAIChatModelProvider = void 0;
const vscode = __importStar(require("vscode"));
const apiClient_1 = require("./apiClient");
const models_1 = require("./models");
class ZAIChatModelProvider {
    constructor(apiKeyManager) {
        this.apiKeyManager = apiKeyManager;
        this.apiClient = new apiClient_1.ZAIAPIClient(apiKeyManager);
    }
    /**
     * Refresh the provider (e.g., when API key changes)
     */
    async refresh() {
        // Trigger a re-fetch of models by creating a new API client
        this.apiClient = new apiClient_1.ZAIAPIClient(this.apiKeyManager);
    }
    /**
     * Provide information about available language models
     */
    async provideLanguageModelChatInformation(options, token) {
        // Check if we have an API key
        const hasKey = await this.apiKeyManager.hasApiKey();
        if (!hasKey) {
            if (!options.silent) {
                const setupAction = 'Setup API Key';
                const result = await vscode.window.showWarningMessage('Z.AI API key not configured. Please set up your API key to use Z.AI models.', setupAction);
                if (result === setupAction) {
                    await vscode.commands.executeCommand('zai.manageApiKey');
                }
            }
            return [];
        }
        // Return the available models
        return models_1.ZAI_MODELS.map(model => ({
            id: model.id,
            name: model.name,
            family: model.family,
            version: model.version,
            maxInputTokens: model.maxInputTokens,
            maxOutputTokens: model.maxOutputTokens,
            tooltip: model.tooltip,
            detail: model.detail,
            capabilities: {
                imageInput: model.capabilities.imageInput,
                toolCalling: model.capabilities.toolCalling
            }
        }));
    }
    /**
     * Handle chat requests and stream responses
     */
    async provideLanguageModelChatResponse(model, messages, options, progress, token) {
        // Get the API key
        const apiKey = await this.apiKeyManager.getApiKey();
        if (!apiKey) {
            throw new Error('Z.AI API key not configured');
        }
        try {
            // Make the API request and stream the response
            await this.apiClient.streamChatCompletion(model.id, messages, options, progress, token);
        }
        catch (error) {
            if (error instanceof Error) {
                if (error.message.includes('401') || error.message.includes('403')) {
                    vscode.window.showErrorMessage('Invalid Z.AI API key. Please check your API key configuration.', 'Setup API Key').then(action => {
                        if (action === 'Setup API Key') {
                            vscode.commands.executeCommand('zai.manageApiKey');
                        }
                    });
                }
                throw error;
            }
            throw new Error(`Unexpected error: ${String(error)}`);
        }
    }
    /**
     * Count tokens in a message
     */
    async provideTokenCount(model, text, token) {
        // Simple estimation: ~4 characters per token
        // This is a rough approximation; ideally you'd use a tokenizer
        let textToCount;
        if (typeof text === 'string') {
            textToCount = text;
        }
        else {
            // Convert message content to string
            textToCount = text.content
                .filter(part => part instanceof vscode.LanguageModelTextPart)
                .map(part => part.value)
                .join('');
        }
        // Approximate token count (4 chars per token is a common estimate)
        return Math.ceil(textToCount.length / 4);
    }
}
exports.ZAIChatModelProvider = ZAIChatModelProvider;
//# sourceMappingURL=provider.js.map