"use strict";
/**
 * HostedApiClient - OpenRouter-based AI client with generous free tier
 *
 * Uses OpenRouter's API with DeepSeek R1 for powerful, free AI generation.
 * Works without API key (with rate limits), or add OPENROUTER_API_KEY for higher limits.
 */
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.HostedApiClient = void 0;
// Polyfill fetch for Node < 18
const node_fetch_1 = __importDefault(require("node-fetch"));
const path = __importStar(require("path"));
const fs = __importStar(require("fs"));
class HostedApiClient {
    constructor(apiKey) {
        // Load model name from config
        this.modelName = this.loadModelFromConfig();
        // Use OpenRouter API
        this.apiUrl =
            process.env.MYCONTEXT_API_URL ||
                "https://openrouter.ai/api/v1/chat/completions";
        // Optional API key for higher limits
        this.apiKey =
            apiKey ||
                process.env.MYCONTEXT_API_KEY ||
                process.env.OPENROUTER_API_KEY ||
                null;
    }
    loadModelFromConfig() {
        try {
            // Try to load from model-versions.json
            const configPath = path.join(__dirname, "../config/model-versions.json");
            if (fs.existsSync(configPath)) {
                const config = JSON.parse(fs.readFileSync(configPath, "utf-8"));
                if (config.current) {
                    return config.current;
                }
            }
        }
        catch (error) {
            // Fallback if config can't be loaded
            console.warn("⚠️  Could not load model config, using default");
        }
        // Fallback to env var or default free model
        return process.env.MYCONTEXT_MODEL_NAME || "deepseek/deepseek-r1";
    }
    async generateText(prompt, options = {}) {
        // Require API key for OpenRouter
        if (!this.apiKey) {
            return {
                success: false,
                error: `OpenRouter API key required. Get your free API key at https://openrouter.ai/keys\n\n` +
                    `Then add it to your .env file:\n` +
                    `MYCONTEXT_OPENROUTER_API_KEY=sk-or-xxx\n\n` +
                    `Or set it directly:\n` +
                    `export MYCONTEXT_OPENROUTER_API_KEY=sk-or-xxx`,
            };
        }
        try {
            const headers = {
                "Content-Type": "application/json",
                "HTTP-Referer": "https://github.com/farajabien/mycontext-cli",
                "X-Title": "MyContext CLI",
                Authorization: `Bearer ${this.apiKey}`,
            };
            console.log(`🔍 DEBUG: Calling OpenRouter API: ${this.apiUrl}`);
            console.log(`🔍 DEBUG: Model: ${this.modelName}`);
            console.log(`🔍 DEBUG: Auth: Yes (API key provided)`);
            const response = await (0, node_fetch_1.default)(this.apiUrl, {
                method: "POST",
                headers,
                body: JSON.stringify({
                    model: this.modelName,
                    messages: [
                        {
                            role: "user",
                            content: prompt,
                        },
                    ],
                    max_tokens: options.maxTokens || 4000,
                    temperature: options.temperature || 0.7,
                }),
            });
            console.log(`🔍 DEBUG: Response status: ${response.status}`);
            if (!response.ok) {
                const errorText = await response.text();
                console.error(`❌ DEBUG: OpenRouter error: ${errorText}`);
                throw new Error(`OpenRouter API error (${response.status}): ${errorText.substring(0, 200)}`);
            }
            const data = await response.json();
            console.log(`🔍 DEBUG: Response data type: ${typeof data}, hasChoices: ${!!data.choices}`);
            // Extract content from OpenRouter response format
            let generatedText = "";
            if (data.choices && data.choices[0]?.message?.content) {
                generatedText = data.choices[0].message.content;
            }
            else {
                console.error(`❌ DEBUG: Unexpected OpenRouter response:`, JSON.stringify(data).substring(0, 500));
                throw new Error("Unexpected OpenRouter response format");
            }
            console.log(`✅ DEBUG: Generated ${generatedText.length} characters`);
            return {
                success: true,
                content: generatedText,
                data: { message: generatedText },
            };
        }
        catch (error) {
            console.error(`❌ DEBUG: Full error:`, error);
            return {
                success: false,
                error: `MyContext AI failed: ${error.message}`,
            };
        }
    }
    async generateComponent(prompt, options = {}) {
        // Use same OpenRouter endpoint as generateText
        return this.generateText(prompt, options);
    }
    async checkConnection() {
        // OpenRouter has generous free tier, always return true
        return true;
    }
    async getPricing() {
        return {
            success: true,
            data: {
                plan: "free",
                description: "OpenRouter free tier with DeepSeek R1",
            },
        };
    }
    async generateContext(type, prompt, options = {}) {
        // Use same OpenRouter endpoint as generateText
        return this.generateText(prompt, options);
    }
    async getUsage(period = "month") {
        return {
            success: true,
            data: {
                message: "Usage tracking not available for OpenRouter free tier",
            },
        };
    }
    async subscribeToPlan(plan, paymentMethod) {
        // Not applicable for OpenRouter free tier
        return {
            success: false,
            error: "Subscriptions not available for OpenRouter free tier",
        };
    }
    hasApiKey() {
        // Always return true since OpenRouter works without auth
        return true;
    }
}
exports.HostedApiClient = HostedApiClient;
//# sourceMappingURL=hostedApiClient.js.map