"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getClaudeSharedSettingsPath = exports.getClaudeExtensionHostMetadata = exports.renderSharedClaudeSettingsJson = exports.renderClaudeExtensionSettingsJson = exports.buildSharedClaudeSettingsObject = exports.buildClaudeExtensionSettingsObject = exports.resolveClaudeExtensionSetup = exports.listClaudeExtensionProfiles = exports.CLAUDE_EXTENSION_MANAGED_ENV_KEYS = void 0;
const profile_detector_1 = require("../auth/profile-detector");
const profile_detector_2 = __importDefault(require("../auth/profile-detector"));
const profile_continuity_inheritance_1 = require("../auth/profile-continuity-inheritance");
const account_context_1 = require("../auth/account-context");
const shared_resource_policy_1 = require("../auth/shared-resource-policy");
const env_builder_1 = require("../cliproxy/config/env-builder");
const port_manager_1 = require("../cliproxy/config/port-manager");
const proxy_target_resolver_1 = require("../cliproxy/proxy/proxy-target-resolver");
const copilot_executor_1 = require("../copilot/copilot-executor");
const cursor_1 = require("../cursor");
const instance_manager_1 = __importDefault(require("../management/instance-manager"));
const shared_manager_1 = __importDefault(require("../management/shared-manager"));
const helpers_1 = require("../utils/helpers");
const claude_config_path_1 = require("../utils/claude-config-path");
const glmt_deprecation_1 = require("../utils/glmt-deprecation");
const claude_extension_hosts_1 = require("./claude-extension-hosts");
exports.CLAUDE_EXTENSION_MANAGED_ENV_KEYS = [
    'ANTHROPIC_API_KEY',
    'ANTHROPIC_AUTH_TOKEN',
    'ANTHROPIC_BASE_URL',
    'ANTHROPIC_MODEL',
    'ANTHROPIC_MAX_TOKENS',
    'ANTHROPIC_SAFE_MODE',
    'ANTHROPIC_TEMPERATURE',
    'ANTHROPIC_SMALL_FAST_MODEL',
    'ANTHROPIC_DEFAULT_OPUS_MODEL',
    'ANTHROPIC_DEFAULT_SONNET_MODEL',
    'ANTHROPIC_DEFAULT_HAIKU_MODEL',
    'API_TIMEOUT_MS',
    'CLAUDE_CONFIG_DIR',
    'DISABLE_NON_ESSENTIAL_MODEL_CALLS',
    'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',
    'ENABLE_STREAMING',
    'MAX_THINKING_TOKENS',
];
function sortUniqueEnvKeys(keys) {
    return [...new Set(keys)].sort((left, right) => left.localeCompare(right));
}
function sortEnvRecord(env) {
    const normalized = {};
    for (const [key, value] of Object.entries(env)) {
        if (typeof value === 'string') {
            normalized[key] = value;
        }
    }
    return Object.fromEntries(Object.entries(normalized).sort(([left], [right]) => left.localeCompare(right)));
}
function describeProfile(profileName, result) {
    if (profileName === 'default') {
        return result.name === 'default'
            ? 'Use Claude Code defaults with no CCS-specific transport override.'
            : `Use the current default profile resolution for "${result.name}".`;
    }
    if (result.type === 'cliproxy')
        return 'OAuth or CLIProxy-backed profile for Anthropic-compatible routing.';
    if (result.type === 'settings') {
        if ((0, glmt_deprecation_1.isDeprecatedGlmtProfileName)(profileName)) {
            return 'Deprecated GLMT compatibility profile normalized to the direct GLM API.';
        }
        return 'API profile backed by a CCS settings file.';
    }
    if (result.type === 'account')
        return 'Claude account instance isolated through CLAUDE_CONFIG_DIR.';
    if (result.type === 'copilot')
        return 'GitHub Copilot profile routed through copilot-api.';
    if (result.type === 'cursor')
        return 'Cursor profile routed through the local cursor daemon.';
    return 'Native Claude profile resolution.';
}
function resultUsesCodexProvider(result) {
    if (result.type !== 'cliproxy') {
        return false;
    }
    if (result.provider === 'codex') {
        return true;
    }
    if (!result.isComposite || !result.compositeTiers) {
        return false;
    }
    return Object.values(result.compositeTiers).some((tier) => tier.provider === 'codex' || tier.fallback?.provider === 'codex');
}
function createCodexClaudeExtensionError(profileName) {
    return new Error(`Profile "${profileName}" is a Codex CLIProxy profile. CCS does not persist Codex CLIProxy profiles into Claude Code or Claude Code Extension settings because that routes Claude traffic through the Codex translator. Use ccsxp or ccs codex --target codex for ChatGPT/Codex subscriptions. To clear stale Claude settings, run ccs persist default --yes.`);
}
function createProfileOption(profileName, result) {
    return {
        name: profileName,
        profileType: result.type,
        label: profileName === 'default' ? 'default' : result.name,
        description: describeProfile(profileName, result),
    };
}
function listClaudeExtensionProfiles() {
    const detector = new profile_detector_2.default();
    const all = detector.getAllProfiles();
    const orderedNames = [
        'default',
        ...all.accounts,
        ...all.settings,
        ...all.cliproxy.filter((profileName) => profileName !== 'cursor'),
        ...all.cliproxyVariants,
    ];
    const deduped = [...new Set(orderedNames)];
    try {
        detector.detectProfileType('copilot');
        deduped.push('copilot');
    }
    catch {
        // Copilot disabled; skip from setup UI.
    }
    try {
        detector.detectProfileType('cursor');
        deduped.push('cursor');
    }
    catch {
        // Cursor disabled; skip from setup UI.
    }
    return deduped
        .map((profileName) => ({ profileName, result: detector.detectProfileType(profileName) }))
        .filter(({ result }) => !resultUsesCodexProvider(result))
        .map(({ profileName, result }) => createProfileOption(profileName, result))
        .sort((left, right) => deduped.indexOf(left.name) - deduped.indexOf(right.name));
}
exports.listClaudeExtensionProfiles = listClaudeExtensionProfiles;
async function resolveExtensionEnv(requestedProfile, result) {
    const warnings = [];
    const notes = [];
    const requestedIsDefault = requestedProfile === 'default';
    if (result.type === 'account') {
        const instanceManager = new instance_manager_1.default();
        const policy = (0, account_context_1.resolveAccountContextPolicy)((0, account_context_1.isAccountContextMetadata)(result.profile) ? result.profile : undefined);
        const sharedResourceMetadata = typeof result.profile === 'object' && result.profile !== null
            ? result.profile
            : undefined;
        const instancePath = await instanceManager.ensureInstance(result.name, policy, {
            bare: (0, shared_resource_policy_1.isProfileLocalSharedResourceMode)(sharedResourceMetadata),
        });
        notes.push('Account profiles authenticate through the isolated Claude config directory.');
        return {
            extensionEnv: { CLAUDE_CONFIG_DIR: instancePath },
            warnings,
            notes,
            disableLoginPrompt: false,
        };
    }
    if (result.type === 'default') {
        const continuity = await (0, profile_continuity_inheritance_1.resolveProfileContinuityInheritance)({
            profileName: requestedProfile,
            profileType: result.type,
            target: 'claude',
        });
        new shared_manager_1.default().normalizeSharedPluginMetadataPathsLocked(continuity.claudeConfigDir);
        if (continuity.claudeConfigDir) {
            notes.push(`Default profile inherits continuity from account "${continuity.sourceAccount}".`);
            return {
                extensionEnv: { CLAUDE_CONFIG_DIR: continuity.claudeConfigDir },
                warnings,
                notes,
                disableLoginPrompt: false,
            };
        }
        notes.push('Default profile clears CCS-managed transport overrides and uses native Claude defaults.');
        return { extensionEnv: {}, warnings, notes, disableLoginPrompt: false };
    }
    const continuity = await (0, profile_continuity_inheritance_1.resolveProfileContinuityInheritance)({
        profileName: requestedProfile,
        profileType: result.type,
        target: 'claude',
    });
    let env = result.type === 'settings'
        ? (result.env ??
            (result.settingsPath ? (0, profile_detector_1.loadSettingsFromFile)((0, helpers_1.expandPath)(result.settingsPath)) : {}))
        : result.type === 'copilot'
            ? (() => {
                if (!result.copilotConfig) {
                    throw new Error(`Profile "${requestedProfile}" is missing copilot configuration.`);
                }
                return (0, copilot_executor_1.generateCopilotEnv)(result.copilotConfig, continuity.claudeConfigDir);
            })()
            : result.type === 'cursor'
                ? (() => {
                    if (!result.cursorConfig) {
                        throw new Error(`Profile "${requestedProfile}" is missing cursor configuration.`);
                    }
                    return (0, cursor_1.generateCursorEnv)(result.cursorConfig, continuity.claudeConfigDir);
                })()
                : (() => {
                    if (!result.provider) {
                        throw new Error(`Profile "${requestedProfile}" is missing CLIProxy provider metadata.`);
                    }
                    const proxyTarget = (0, proxy_target_resolver_1.getProxyTarget)();
                    const port = result.port || port_manager_1.CLIPROXY_DEFAULT_PORT;
                    if (proxyTarget.isRemote) {
                        warnings.push(`CLIProxy is configured for remote routing via ${proxyTarget.protocol}://${proxyTarget.host}:${proxyTarget.port}.`);
                        return result.isComposite && result.compositeTiers && result.compositeDefaultTier
                            ? (0, env_builder_1.getCompositeEnvVars)(result.compositeTiers, result.compositeDefaultTier, port, result.settingsPath, proxyTarget)
                            : (0, env_builder_1.getRemoteEnvVars)(result.provider, proxyTarget, result.settingsPath);
                    }
                    warnings.push('CLIProxy-backed profiles require the local or remote proxy endpoint to be reachable.');
                    return result.isComposite && result.compositeTiers && result.compositeDefaultTier
                        ? (0, env_builder_1.getCompositeEnvVars)(result.compositeTiers, result.compositeDefaultTier, port, result.settingsPath)
                        : (0, env_builder_1.getEffectiveEnvVars)(result.provider, port, result.settingsPath);
                })();
    if (result.type === 'settings' && (0, glmt_deprecation_1.isDeprecatedGlmtProfileName)(requestedProfile)) {
        const normalized = (0, glmt_deprecation_1.normalizeDeprecatedGlmtEnv)(sortEnvRecord(env));
        env = normalized.env;
        warnings.push(...normalized.warnings);
        notes.push('Create or migrate to a glm profile when convenient to remove legacy GLMT config.');
    }
    if (!requestedIsDefault && continuity.claudeConfigDir && !env.CLAUDE_CONFIG_DIR) {
        env.CLAUDE_CONFIG_DIR = continuity.claudeConfigDir;
        notes.push(`Continuity inheritance adds CLAUDE_CONFIG_DIR from account "${continuity.sourceAccount}".`);
    }
    new shared_manager_1.default().normalizeSharedPluginMetadataPathsLocked(env.CLAUDE_CONFIG_DIR);
    if (result.type === 'copilot') {
        warnings.push('copilot-api must stay reachable for this profile to work inside the IDE extension.');
    }
    if (result.type === 'cursor') {
        warnings.push('The local Cursor daemon must stay reachable for this profile to work inside the IDE extension.');
    }
    if (Object.keys(env).length === 0) {
        throw new Error(`Profile "${requestedProfile}" has no extension environment to export.`);
    }
    return { extensionEnv: sortEnvRecord(env), warnings, notes, disableLoginPrompt: true };
}
async function resolveClaudeExtensionSetup(requestedProfile) {
    const detector = new profile_detector_2.default();
    const result = detector.detectProfileType(requestedProfile);
    if (resultUsesCodexProvider(result)) {
        throw createCodexClaudeExtensionError(requestedProfile);
    }
    const resolved = await resolveExtensionEnv(requestedProfile, result);
    return {
        requestedProfile,
        resolvedProfileName: result.name,
        profileType: result.type,
        profileLabel: requestedProfile === 'default' ? 'default' : result.name,
        profileDescription: describeProfile(requestedProfile, result),
        extensionEnv: resolved.extensionEnv,
        removeEnvKeys: sortUniqueEnvKeys([
            ...exports.CLAUDE_EXTENSION_MANAGED_ENV_KEYS,
            ...Object.keys(resolved.extensionEnv),
        ]),
        warnings: resolved.warnings,
        notes: resolved.notes,
        disableLoginPrompt: resolved.disableLoginPrompt,
    };
}
exports.resolveClaudeExtensionSetup = resolveClaudeExtensionSetup;
function buildClaudeExtensionSettingsObject(setup, host) {
    const definition = (0, claude_extension_hosts_1.getClaudeExtensionHostDefinition)(host);
    const payload = {
        [definition.settingsKey]: Object.entries(setup.extensionEnv).map(([name, value]) => ({
            name,
            value,
        })),
    };
    if (definition.disableLoginPromptKey && setup.disableLoginPrompt) {
        payload[definition.disableLoginPromptKey] = true;
    }
    return payload;
}
exports.buildClaudeExtensionSettingsObject = buildClaudeExtensionSettingsObject;
function buildSharedClaudeSettingsObject(setup) {
    return { env: setup.extensionEnv };
}
exports.buildSharedClaudeSettingsObject = buildSharedClaudeSettingsObject;
function renderClaudeExtensionSettingsJson(setup, host) {
    return JSON.stringify(buildClaudeExtensionSettingsObject(setup, host), null, 2);
}
exports.renderClaudeExtensionSettingsJson = renderClaudeExtensionSettingsJson;
function renderSharedClaudeSettingsJson(setup) {
    return JSON.stringify(buildSharedClaudeSettingsObject(setup), null, 2);
}
exports.renderSharedClaudeSettingsJson = renderSharedClaudeSettingsJson;
function getClaudeExtensionHostMetadata(host) {
    return (0, claude_extension_hosts_1.getClaudeExtensionHostDefinition)(host);
}
exports.getClaudeExtensionHostMetadata = getClaudeExtensionHostMetadata;
function getClaudeSharedSettingsPath() {
    return (0, claude_config_path_1.getClaudeSettingsPath)();
}
exports.getClaudeSharedSettingsPath = getClaudeSharedSettingsPath;
//# sourceMappingURL=claude-extension-setup.js.map