"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 (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.resolveCliproxyBridgeMetadata = exports.resolveCliproxyBridgeProfile = exports.listCliproxyBridgeProviders = exports.suggestCliproxyBridgeName = exports.getDefaultCliproxyBridgeName = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const proxy_target_resolver_1 = require("../../cliproxy/proxy/proxy-target-resolver");
const auth_token_manager_1 = require("../../cliproxy/auth/auth-token-manager");
const base_config_loader_1 = require("../../cliproxy/config/base-config-loader");
const provider_capabilities_1 = require("../../cliproxy/provider-capabilities");
const model_id_normalizer_1 = require("../../cliproxy/ai-providers/model-id-normalizer");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const DEFAULT_PROFILE_SUFFIX = '-api';
function normalizeBridgeUrl(value) {
    try {
        const parsed = new URL(value);
        const hostname = parsed.hostname === 'localhost' ? '127.0.0.1' : parsed.hostname;
        const pathname = parsed.pathname.replace(/\/+$/, '') || '/';
        return `${parsed.protocol}//${hostname}:${parsed.port}${pathname}`;
    }
    catch {
        return value.trim().replace(/\/+$/, '');
    }
}
function resolveProviderFromBaseUrl(baseUrl) {
    if (typeof baseUrl !== 'string' || baseUrl.trim().length === 0) {
        return null;
    }
    try {
        const parsed = new URL(baseUrl);
        const extracted = (0, model_id_normalizer_1.extractProviderFromPathname)(parsed.pathname);
        return extracted ? (0, provider_capabilities_1.mapExternalProviderName)(extracted) : null;
    }
    catch {
        const extracted = (0, model_id_normalizer_1.extractProviderFromPathname)(baseUrl);
        return extracted ? (0, provider_capabilities_1.mapExternalProviderName)(extracted) : null;
    }
}
function hasConfiguredProfile(name) {
    if ((0, config_loader_facade_1.isUnifiedMode)()) {
        const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
        return name in config.profiles;
    }
    const config = (0, config_loader_facade_1.loadConfigSafe)();
    return name in config.profiles;
}
function hasSettingsFile(name) {
    return fs.existsSync(path.join((0, config_loader_facade_1.getCcsDir)(), `${name}.settings.json`));
}
function getDefaultCliproxyBridgeName(provider) {
    return `${provider}${DEFAULT_PROFILE_SUFFIX}`;
}
exports.getDefaultCliproxyBridgeName = getDefaultCliproxyBridgeName;
function suggestCliproxyBridgeName(provider) {
    const baseName = getDefaultCliproxyBridgeName(provider);
    if (!hasConfiguredProfile(baseName) && !hasSettingsFile(baseName)) {
        return baseName;
    }
    for (let index = 2; index < 1000; index += 1) {
        const candidate = `${baseName}-${index}`;
        if (!hasConfiguredProfile(candidate) && !hasSettingsFile(candidate)) {
            return candidate;
        }
    }
    return `${baseName}-${Date.now()}`;
}
exports.suggestCliproxyBridgeName = suggestCliproxyBridgeName;
function resolveBridgeModelMapping(provider) {
    const mapping = (0, base_config_loader_1.getModelMappingFromConfig)(provider);
    return {
        default: mapping.defaultModel,
        opus: mapping.opusModel || mapping.defaultModel,
        sonnet: mapping.sonnetModel || mapping.defaultModel,
        haiku: mapping.haikuModel || mapping.defaultModel,
    };
}
function listCliproxyBridgeProviders() {
    return provider_capabilities_1.CLIPROXY_PROVIDER_IDS.map((provider) => ({
        provider,
        displayName: (0, provider_capabilities_1.getProviderDisplayName)(provider),
        description: (0, provider_capabilities_1.getProviderDescription)(provider),
        defaultProfileName: getDefaultCliproxyBridgeName(provider),
        routePath: `/api/provider/${provider}`,
    }));
}
exports.listCliproxyBridgeProviders = listCliproxyBridgeProviders;
function resolveCliproxyBridgeProfile(provider, options = {}) {
    const target = (0, proxy_target_resolver_1.getProxyTarget)();
    const profileName = options.name?.trim() || suggestCliproxyBridgeName(provider);
    const baseUrl = (0, proxy_target_resolver_1.buildProxyUrl)(target, `/api/provider/${provider}`);
    const apiKey = target.authToken ?? (0, auth_token_manager_1.getEffectiveApiKey)();
    return {
        name: profileName,
        provider,
        providerDisplayName: (0, provider_capabilities_1.getProviderDisplayName)(provider),
        baseUrl,
        apiKey,
        models: resolveBridgeModelMapping(provider),
        target: options.target || 'claude',
        routePath: `/api/provider/${provider}`,
        source: target.isRemote ? 'remote' : 'local',
    };
}
exports.resolveCliproxyBridgeProfile = resolveCliproxyBridgeProfile;
function resolveCliproxyBridgeMetadata(settings) {
    const provider = resolveProviderFromBaseUrl(settings?.env?.ANTHROPIC_BASE_URL);
    if (!provider) {
        return null;
    }
    const resolved = resolveCliproxyBridgeProfile(provider);
    const actualBaseUrl = settings?.env?.ANTHROPIC_BASE_URL?.trim() || '';
    const actualAuthToken = settings?.env?.ANTHROPIC_AUTH_TOKEN?.trim() || '';
    return {
        provider,
        providerDisplayName: resolved.providerDisplayName,
        routePath: resolved.routePath,
        currentBaseUrl: resolved.baseUrl,
        source: resolved.source,
        usesCurrentTarget: normalizeBridgeUrl(actualBaseUrl) === normalizeBridgeUrl(resolved.baseUrl),
        usesCurrentAuthToken: actualAuthToken.length > 0 && actualAuthToken === resolved.apiKey,
    };
}
exports.resolveCliproxyBridgeMetadata = resolveCliproxyBridgeMetadata;
//# sourceMappingURL=cliproxy-profile-bridge.js.map