"use strict";
/**
 * API Profile Reader Service
 *
 * Read operations for API profiles.
 * Supports both unified YAML config and legacy JSON config.
 */
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.isUsingUnifiedConfig = exports.getApiProfileNames = exports.listApiProfiles = exports.isApiProfileConfigured = exports.apiProfileExists = void 0;
const fs = __importStar(require("fs"));
const helpers_1 = require("../../utils/helpers");
const target_metadata_1 = require("../../targets/target-metadata");
const cliproxy_profile_bridge_1 = require("./cliproxy-profile-bridge");
const config_loader_facade_1 = require("../../config/config-loader-facade");
function sanitizeTarget(target) {
    if ((0, target_metadata_1.isPersistedTargetType)(target)) {
        return target;
    }
    return 'claude';
}
/**
 * Check if API profile exists in config
 */
function apiProfileExists(name) {
    try {
        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;
    }
    catch {
        return false;
    }
}
exports.apiProfileExists = apiProfileExists;
/**
 * Load settings file from a config reference such as ~/.ccs/name.settings.json.
 */
function loadProfileSettings(settingsReference) {
    if (!settingsReference || settingsReference === 'config.yaml') {
        return null;
    }
    try {
        const settingsPath = (0, helpers_1.expandPath)(settingsReference);
        if (!fs.existsSync(settingsPath))
            return null;
        return JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
    }
    catch {
        return null;
    }
}
function isConfiguredFromSettings(settings) {
    const token = settings?.env?.ANTHROPIC_AUTH_TOKEN || settings?.env?.ANTHROPIC_API_KEY || '';
    return token.length > 0 && !token.includes('YOUR_') && !token.includes('your-');
}
function resolveProfileSettingsReference(name) {
    if ((0, config_loader_facade_1.isUnifiedMode)()) {
        const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
        return config.profiles[name]?.settings;
    }
    const config = (0, config_loader_facade_1.loadConfigSafe)();
    return config.profiles[name];
}
/**
 * Check if API profile has real API key (not placeholder)
 */
function isApiProfileConfigured(apiName) {
    return isConfiguredFromSettings(loadProfileSettings(resolveProfileSettingsReference(apiName)));
}
exports.isApiProfileConfigured = isApiProfileConfigured;
/**
 * List all API profiles
 *
 * Note: The 'default' profile (pointing to ~/.claude/settings.json) is excluded
 * as it represents the user's native Claude subscription, not an API profile.
 */
function listApiProfiles() {
    const profiles = [];
    const variants = [];
    if ((0, config_loader_facade_1.isUnifiedMode)()) {
        const unifiedConfig = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
        for (const [name, profile] of Object.entries(unifiedConfig.profiles)) {
            // Skip 'default' profile - it's the user's native Claude settings
            if (name === 'default' && profile.settings?.includes('.claude/settings.json')) {
                continue;
            }
            const settingsPath = profile.settings || 'config.yaml';
            const settings = loadProfileSettings(settingsPath);
            profiles.push({
                name,
                settingsPath,
                isConfigured: isConfiguredFromSettings(settings),
                configSource: 'unified',
                target: sanitizeTarget(profile.target),
                cliproxyBridge: (0, cliproxy_profile_bridge_1.resolveCliproxyBridgeMetadata)(settings),
            });
        }
        // CLIProxy variants
        for (const [name, variant] of Object.entries(unifiedConfig.cliproxy?.variants || {})) {
            const provider = variant && 'type' in variant && variant.type === 'composite'
                ? 'composite'
                : variant?.provider || 'unknown';
            variants.push({
                name,
                provider,
                settings: variant?.settings || '-',
                target: sanitizeTarget(variant?.target),
            });
        }
    }
    else {
        const config = (0, config_loader_facade_1.loadConfigSafe)();
        const legacyTargetMap = config
            .profile_targets;
        for (const [name, settingsPath] of Object.entries(config.profiles)) {
            // Skip 'default' profile - it's the user's native Claude settings
            if (name === 'default' && settingsPath.includes('.claude/settings.json')) {
                continue;
            }
            const settings = loadProfileSettings(settingsPath);
            profiles.push({
                name,
                settingsPath: settingsPath,
                isConfigured: isConfiguredFromSettings(settings),
                configSource: 'legacy',
                target: sanitizeTarget(legacyTargetMap?.[name]),
                cliproxyBridge: (0, cliproxy_profile_bridge_1.resolveCliproxyBridgeMetadata)(settings),
            });
        }
        // CLIProxy variants
        if (config.cliproxy) {
            for (const [name, v] of Object.entries(config.cliproxy)) {
                const variant = v;
                variants.push({
                    name,
                    provider: variant.provider,
                    settings: variant.settings,
                    target: sanitizeTarget(variant.target),
                });
            }
        }
    }
    return { profiles, variants };
}
exports.listApiProfiles = listApiProfiles;
/**
 * Get list of available API profile names
 */
function getApiProfileNames() {
    if ((0, config_loader_facade_1.isUnifiedMode)()) {
        const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
        return Object.keys(config.profiles);
    }
    const config = (0, config_loader_facade_1.loadConfigSafe)();
    return Object.keys(config.profiles);
}
exports.getApiProfileNames = getApiProfileNames;
/**
 * Check if using unified config mode
 */
function isUsingUnifiedConfig() {
    return (0, config_loader_facade_1.isUnifiedMode)();
}
exports.isUsingUnifiedConfig = isUsingUnifiedConfig;
//# sourceMappingURL=profile-reader.js.map