"use strict";
/**
 * Proxy Chain Builder (Concern F — tool-sanitization + codex-reasoning layers)
 *
 * Orchestrates the two env-dependent proxy layers that sit between the
 * Claude CLI process and the upstream CLIProxy / remote endpoint:
 *
 *   1. ToolSanitizationProxy — wraps ANTHROPIC_BASE_URL to sanitize tool names/schemas
 *   2. CodexReasoningProxy   — only for single-provider codex, wraps tool-san URL
 *
 * Placement in the execution sequence
 * ─────────────────────────────────────
 * The HTTPS tunnel (HttpsTunnelProxy) is started BEFORE this function is called,
 * because its tunnelPort is needed by both imageAnalysisResolution and the
 * first-pass buildClaudeEnvironment.  This function receives the result of that
 * first-pass env as `initialEnvVars`, from which it extracts ANTHROPIC_BASE_URL
 * to wire up the tool-sanitization proxy.
 *
 * Lifecycle: proxies are started (spawned) but NOT stopped here.  The caller
 * is responsible for registering cleanup handlers (setupCleanupHandlers).
 */
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.buildProxyChain = void 0;
const path = __importStar(require("path"));
const ui_1 = require("../../utils/ui");
const config_loader_facade_1 = require("../../config/config-loader-facade");
const tool_sanitization_proxy_1 = require("../proxy/tool-sanitization-proxy");
const codex_reasoning_proxy_1 = require("../ai-providers/codex-reasoning-proxy");
const thinking_override_resolver_1 = require("./thinking-override-resolver");
// ── Implementation ────────────────────────────────────────────────────────────
/**
 * Build and start the two env-dependent proxy layers (tool-sanitization and
 * codex-reasoning).  Each layer is started independently; a failed start is
 * swallowed with a verbose warning so the session can continue degraded.
 *
 * Note: HttpsTunnelProxy is started inline in the orchestrator (index.ts)
 * before this function is called, because tunnelPort is required for
 * imageAnalysisResolution and the first-pass buildClaudeEnvironment.
 */
async function buildProxyChain(context) {
    const { provider, useRemoteProxy, proxyConfig, cfg, initialEnvVars, thinkingOverride, thinkingCfg, verbose, log, 
    // Allow test injection of proxy constructors so tests never spin up real servers
    _ToolSanitizationProxy: ToolSanitizationProxyImpl = tool_sanitization_proxy_1.ToolSanitizationProxy, _CodexReasoningProxy: CodexReasoningProxyImpl = codex_reasoning_proxy_1.CodexReasoningProxy, } = context;
    // ── Step 1: Tool sanitization proxy ────────────────────────────────────────
    let toolSanitizationProxy = null;
    let toolSanitizationPort = null;
    if (initialEnvVars.ANTHROPIC_BASE_URL) {
        try {
            toolSanitizationProxy = new ToolSanitizationProxyImpl({
                upstreamBaseUrl: initialEnvVars.ANTHROPIC_BASE_URL,
                verbose,
                warnOnSanitize: true,
                allowSelfSigned: useRemoteProxy ? (proxyConfig.allowSelfSigned ?? false) : false,
            });
            toolSanitizationPort = await toolSanitizationProxy.start();
            log(`Tool sanitization proxy active on port ${toolSanitizationPort}`);
        }
        catch (error) {
            const err = error;
            toolSanitizationProxy = null;
            toolSanitizationPort = null;
            if (verbose) {
                console.error((0, ui_1.warn)(`Tool sanitization proxy disabled: ${err.message}`));
            }
        }
    }
    // ── Step 2: Codex reasoning proxy ──────────────────────────────────────────
    let codexReasoningProxy = null;
    let codexReasoningPort = null;
    // Composite variants require root model-routed endpoints, never provider-pinned codex endpoints.
    if (provider === 'codex' && !cfg.isComposite) {
        const postSanitizationBaseUrl = toolSanitizationPort
            ? `http://127.0.0.1:${toolSanitizationPort}`
            : initialEnvVars.ANTHROPIC_BASE_URL;
        if (!postSanitizationBaseUrl) {
            log('ANTHROPIC_BASE_URL not set for Codex, reasoning proxy disabled');
        }
        else {
            try {
                const traceEnabled = process.env.CCS_CODEX_REASONING_TRACE === '1' ||
                    process.env.CCS_CODEX_REASONING_TRACE === 'true';
                const stripPathPrefix = useRemoteProxy ? '/api/provider/codex' : undefined;
                const codexThinkingOff = (0, thinking_override_resolver_1.shouldDisableCodexReasoning)(thinkingCfg, thinkingOverride);
                codexReasoningProxy = new CodexReasoningProxyImpl({
                    upstreamBaseUrl: postSanitizationBaseUrl,
                    verbose,
                    defaultEffort: 'medium',
                    disableEffort: codexThinkingOff,
                    traceFilePath: traceEnabled ? path.join((0, config_loader_facade_1.getCcsDir)(), 'codex-reasoning-proxy.log') : '',
                    allowSelfSigned: useRemoteProxy ? (proxyConfig.allowSelfSigned ?? false) : false,
                    modelMap: {
                        defaultModel: initialEnvVars.ANTHROPIC_MODEL,
                        opusModel: initialEnvVars.ANTHROPIC_DEFAULT_OPUS_MODEL,
                        sonnetModel: initialEnvVars.ANTHROPIC_DEFAULT_SONNET_MODEL,
                        haikuModel: initialEnvVars.ANTHROPIC_DEFAULT_HAIKU_MODEL,
                    },
                    stripPathPrefix,
                });
                codexReasoningPort = await codexReasoningProxy.start();
                log(`Codex reasoning proxy active: http://127.0.0.1:${codexReasoningPort}/api/provider/codex`);
            }
            catch (error) {
                const err = error;
                codexReasoningProxy = null;
                codexReasoningPort = null;
                if (verbose) {
                    console.error((0, ui_1.warn)(`Codex reasoning proxy disabled: ${err.message}`));
                }
            }
        }
    }
    return {
        toolSanitizationProxy,
        toolSanitizationPort,
        codexReasoningProxy,
        codexReasoningPort,
    };
}
exports.buildProxyChain = buildProxyChain;
//# sourceMappingURL=proxy-chain-builder.js.map