"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;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.GitHubModelsClient = void 0;
const axios_1 = __importDefault(require("axios"));
const chalk_1 = __importDefault(require("chalk"));
class GitHubModelsClient {
    constructor() {
        this.clientType = "direct-api";
        this.supportsTools = false;
        this.supportsStreaming = false;
        this.baseUrl = "https://models.inference.ai.azure.com";
        this.apiKey =
            process.env.GITHUB_TOKEN ||
                process.env.GITHUB_MODELS_API_KEY ||
                process.env.MYCONTEXT_GITHUB_TOKEN;
    }
    hasApiKey() {
        return !!this.apiKey;
    }
    setApiKey(apiKey) {
        this.apiKey = apiKey;
    }
    /**
     * Check connection to GitHub Models API
     */
    async checkConnection() {
        if (!this.apiKey)
            return false;
        try {
            // Try to list models as a connection test
            await axios_1.default.get(`${this.baseUrl}/models`, {
                headers: {
                    Authorization: `Bearer ${this.apiKey}`,
                },
            });
            return true;
        }
        catch (error) {
            return false;
        }
    }
    /**
     * Generate text using GitHub Models
     */
    async generateText(prompt, options = {}) {
        if (!this.apiKey) {
            throw new Error("GITHUB_TOKEN or GITHUB_MODELS_API_KEY not found in environment");
        }
        const model = options.model || "gpt-4o";
        const temperature = options.temperature || 0.7;
        const maxTokens = options.maxTokens || 4000;
        try {
            if (process.env.DEBUG || process.env.VERBOSE) {
                console.log(chalk_1.default.gray(`[GitHubModelsClient] Generating text with model: ${model}`));
            }
            const postData = {
                model,
                messages: [{ role: "user", content: prompt }],
                temperature,
                max_tokens: maxTokens,
            };
            const response = await axios_1.default.post(`${this.baseUrl}/chat/completions`, postData, {
                headers: {
                    Authorization: `Bearer ${this.apiKey}`,
                    "Content-Type": "application/json",
                },
            });
            return response.data.choices[0].message.content;
        }
        catch (error) {
            const message = error.response?.data?.error?.message || error.message;
            throw new Error(`GitHub Models generation failed: ${message}`);
        }
    }
    /**
     * Generate component using GitHub Models
     */
    async generateComponent(prompt, context, options = {}) {
        const systemPrompt = `You are an expert React developer. 
Generate a high-quality, responsive React component using Tailwind CSS.
Include necessary imports (Lucide, Radix, etc. as needed).
Return ONLY the code block.`;
        const fullPrompt = `${systemPrompt}\n\nTask: ${prompt}`;
        return this.generateText(fullPrompt, options);
    }
    /**
     * Generate component refinement
     */
    async generateComponentRefinement(componentCode, prompt, context, options = {}) {
        const systemPrompt = `You are an expert React developer. 
Refine the provided React component based on the user request. 
Maintain high quality, responsiveness, and Tailwind CSS patterns.
Return ONLY the updated code block.`;
        const fullPrompt = `${systemPrompt}\n\nExisting Code:\n\`\`\`tsx\n${componentCode}\n\`\`\`\n\nRequest: ${prompt}`;
        return this.generateText(fullPrompt, options);
    }
    /**
     * Generate text from image using GitHub Models (GPT-4o Vision)
     */
    async generateVisionText(prompt, imagePath, options = {}) {
        if (!this.apiKey) {
            throw new Error("GITHUB_TOKEN or GITHUB_MODELS_API_KEY not found in environment");
        }
        const model = options.model || "gpt-4o";
        try {
            const fs = await Promise.resolve().then(() => __importStar(require("fs")));
            const imageData = await fs.promises.readFile(imagePath);
            const base64Image = imageData.toString("base64");
            const mimeType = imagePath.toLowerCase().endsWith(".png") ? "image/png" : "image/jpeg";
            const postData = {
                model,
                messages: [
                    {
                        role: "user",
                        content: [
                            { type: "text", text: prompt },
                            {
                                type: "image_url",
                                image_url: {
                                    url: `data:${mimeType};base64,${base64Image}`,
                                },
                            },
                        ],
                    },
                ],
                max_tokens: options.maxTokens || 4000,
            };
            const response = await axios_1.default.post(`${this.baseUrl}/chat/completions`, postData, {
                headers: {
                    Authorization: `Bearer ${this.apiKey}`,
                    "Content-Type": "application/json",
                },
            });
            return response.data.choices[0].message.content;
        }
        catch (error) {
            const message = error.response?.data?.error?.message || error.message;
            throw new Error(`GitHub Models vision generation failed: ${message}`);
        }
    }
    /**
     * Generate image using GitHub Models
     */
    async generateImage(prompt, outputPath, options = {}) {
        throw new Error("GitHub Models image generation not yet implemented in this client");
    }
    /**
     * List available models (placeholder - can be expanded)
     */
    async listModels() {
        return ["gpt-4o", "gpt-4o-mini", "o1-preview", "o1-mini"];
    }
    /**
     * Cleanup resources
     */
    async cleanup() {
        // No specific cleanup needed
    }
}
exports.GitHubModelsClient = GitHubModelsClient;
//# sourceMappingURL=githubModelsClient.js.map