"use strict";
/**
 * API Key Pre-flight Validator
 *
 * Quick validation of API keys before Claude CLI launch.
 * Catches expired keys early with actionable error messages.
 */
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 (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateAnthropicKey = exports.validateMiniMaxKey = exports.validateGlmKey = void 0;
const http = __importStar(require("http"));
const https = __importStar(require("https"));
const url_1 = require("url");
/** Default placeholders that indicate unconfigured keys */
const DEFAULT_PLACEHOLDERS = [
    'YOUR_GLM_API_KEY_HERE',
    'YOUR_KIMI_API_KEY_HERE',
    'YOUR_MINIMAX_API_KEY_HERE',
    'YOUR_API_KEY_HERE',
    'YOUR-API-KEY-HERE',
    'PLACEHOLDER',
    '',
];
async function validateProviderKey(apiKey, config, baseUrl, timeoutMs = 2000) {
    if (process.env.CCS_SKIP_PREFLIGHT === '1') {
        return { valid: true };
    }
    if (!apiKey || DEFAULT_PLACEHOLDERS.includes(apiKey.toUpperCase())) {
        return {
            valid: false,
            error: 'API key not configured',
            suggestion: `Set ANTHROPIC_AUTH_TOKEN in ~/.ccs/${config.profile}.settings.json\n` +
                `Or run: ccs config -> API Profiles -> ${config.name}`,
        };
    }
    const targetBase = baseUrl || config.defaultBaseUrl;
    let url;
    try {
        url = new url_1.URL(config.path, targetBase);
    }
    catch {
        return { valid: true };
    }
    return new Promise((resolve) => {
        let resolved = false;
        const safeResolve = (result) => {
            if (resolved)
                return;
            resolved = true;
            resolve(result);
        };
        const isHttps = url.protocol === 'https:';
        const httpModule = isHttps ? https : http;
        const defaultPort = isHttps ? 443 : 80;
        const options = {
            hostname: url.hostname,
            port: url.port || defaultPort,
            path: url.pathname,
            method: 'GET',
            headers: {
                Authorization: `Bearer ${apiKey}`,
                'User-Agent': 'CCS-Preflight/1.0',
            },
        };
        const req = httpModule.request(options, (res) => {
            clearTimeout(timeoutId);
            if (res.statusCode === 200) {
                safeResolve({ valid: true });
            }
            else if (res.statusCode === 401 || res.statusCode === 403) {
                safeResolve({
                    valid: false,
                    error: `API key rejected by ${config.displayName}`,
                    suggestion: `Your key may have expired. To fix:\n` +
                        `  1. Go to ${config.dashboardUrl} and regenerate your API key\n` +
                        `  2. Update ~/.ccs/${config.profile}.settings.json with new key\n` +
                        `  3. Or run: ccs config -> API Profiles -> ${config.name}`,
                });
            }
            else {
                if (process.env.CCS_DEBUG === '1') {
                    console.error(`[CCS-Preflight] Unexpected status ${res.statusCode} from ${url.href} - fail-open`);
                }
                safeResolve({ valid: true });
            }
            res.resume();
        });
        req.on('error', () => {
            clearTimeout(timeoutId);
            safeResolve({ valid: true });
        });
        const timeoutId = setTimeout(() => {
            req.destroy();
            safeResolve({ valid: true });
        }, timeoutMs);
        req.end();
    });
}
async function validateGlmKey(apiKey, baseUrl, timeoutMs) {
    return validateProviderKey(apiKey, {
        name: 'GLM',
        profile: 'glm',
        defaultBaseUrl: 'https://api.z.ai',
        path: '/api/anthropic/v1/models',
        displayName: 'Z.AI',
        dashboardUrl: 'Z.AI dashboard',
    }, baseUrl, timeoutMs);
}
exports.validateGlmKey = validateGlmKey;
async function validateMiniMaxKey(apiKey, baseUrl, timeoutMs) {
    return validateProviderKey(apiKey, {
        name: 'MiniMax',
        profile: 'mm',
        defaultBaseUrl: 'https://api.minimax.io',
        path: '/anthropic/v1/models',
        displayName: 'MiniMax',
        dashboardUrl: 'platform.minimax.io',
    }, baseUrl, timeoutMs);
}
exports.validateMiniMaxKey = validateMiniMaxKey;
/** Validate Anthropic direct API key using x-api-key header (not Bearer) */
async function validateAnthropicKey(apiKey, timeoutMs = 2000) {
    if (process.env.CCS_SKIP_PREFLIGHT === '1') {
        return { valid: true };
    }
    if (!apiKey || DEFAULT_PLACEHOLDERS.includes(apiKey.toUpperCase())) {
        return {
            valid: false,
            error: 'Anthropic API key not configured',
            suggestion: 'Set ANTHROPIC_API_KEY in your profile settings.json',
        };
    }
    return new Promise((resolve) => {
        let resolved = false;
        const safeResolve = (result) => {
            if (resolved)
                return;
            resolved = true;
            resolve(result);
        };
        const options = {
            hostname: 'api.anthropic.com',
            port: 443,
            path: '/v1/models',
            method: 'GET',
            headers: {
                'x-api-key': apiKey,
                'anthropic-version': '2023-06-01',
                'User-Agent': 'CCS-Preflight/1.0',
            },
        };
        const req = https.request(options, (res) => {
            clearTimeout(timeoutId);
            if (res.statusCode === 200) {
                safeResolve({ valid: true });
            }
            else if (res.statusCode === 401 || res.statusCode === 403) {
                safeResolve({
                    valid: false,
                    error: 'Anthropic API key rejected',
                    suggestion: 'Your key may have expired. To fix:\n' +
                        '  1. Go to console.anthropic.com/settings/keys and regenerate your API key\n' +
                        '  2. Update ANTHROPIC_API_KEY in your profile settings.json\n' +
                        '  3. Or run: ccs api create --preset anthropic',
                });
            }
            else {
                safeResolve({ valid: true });
            }
            res.resume();
        });
        req.on('error', () => {
            clearTimeout(timeoutId);
            safeResolve({ valid: true });
        });
        const timeoutId = setTimeout(() => {
            req.destroy();
            safeResolve({ valid: true });
        }, timeoutMs);
        req.end();
    });
}
exports.validateAnthropicKey = validateAnthropicKey;
//# sourceMappingURL=api-key-validator.js.map