"use strict";
/**
 * Image Analysis Hook Environment Variables
 *
 * Provides environment variables for image analysis hook configuration.
 * Hook routes image/PDF files through CLIProxy for vision analysis.
 *
 * @module utils/hooks/image-analysis-hook-env
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.applyImageAnalysisRuntimeOverrides = exports.getImageAnalysisHookEnv = exports.resolveImageAnalysisRuntimeConnection = void 0;
const cliproxy_profile_bridge_1 = require("../../api/services/cliproxy-profile-bridge");
const auth_token_manager_1 = require("../../cliproxy/auth/auth-token-manager");
const provider_capabilities_1 = require("../../cliproxy/provider-capabilities");
const proxy_target_resolver_1 = require("../../cliproxy/proxy/proxy-target-resolver");
const hook_installer_1 = require("../image-analysis/hook-installer");
const image_analysis_backend_resolver_1 = require("./image-analysis-backend-resolver");
const config_loader_facade_1 = require("../../config/config-loader-facade");
/**
 * Serialize provider_models map to env var format: provider:model,provider:model
 */
function serializeProviderModels(providerModels) {
    return Object.entries(providerModels)
        .map(([provider, model]) => `${provider}:${model}`)
        .join(',');
}
function stripTrailingSlash(value) {
    return value.replace(/\/+$/, '');
}
function resolveImageAnalysisRuntimeConnection(options = {}) {
    const proxyTarget = options.proxyTarget ?? (0, proxy_target_resolver_1.getProxyTarget)();
    const apiKey = proxyTarget.authToken?.trim() || (0, auth_token_manager_1.getEffectiveApiKey)();
    if (proxyTarget.isRemote && options.tunnelPort && options.tunnelPort > 0) {
        return {
            baseUrl: `http://127.0.0.1:${options.tunnelPort}`,
            apiKey,
            allowSelfSigned: false,
            proxyTarget: {
                host: '127.0.0.1',
                port: options.tunnelPort,
                protocol: 'http',
                isRemote: false,
            },
        };
    }
    return {
        baseUrl: stripTrailingSlash((0, proxy_target_resolver_1.buildProxyUrl)(proxyTarget, '')),
        apiKey,
        allowSelfSigned: Boolean(proxyTarget.isRemote && proxyTarget.protocol === 'https' && proxyTarget.allowSelfSigned),
        proxyTarget,
    };
}
exports.resolveImageAnalysisRuntimeConnection = resolveImageAnalysisRuntimeConnection;
/**
 * Get image analysis hook environment variables.
 * These env vars control the hook's behavior via Claude Code hook system.
 *
 * @param input - Current runtime context
 * @returns Environment variables for image analysis hook
 */
function getImageAnalysisHookEnv(input) {
    const config = (0, config_loader_facade_1.getImageAnalysisConfig)();
    const context = typeof input === 'string'
        ? {
            profileName: input,
            cliproxyProvider: (0, provider_capabilities_1.mapExternalProviderName)(input) ?? undefined,
        }
        : input;
    const status = context
        ? (0, image_analysis_backend_resolver_1.resolveImageAnalysisStatus)(context, config)
        : (0, image_analysis_backend_resolver_1.resolveImageAnalysisStatus)({ profileName: '' }, config);
    const skipImageAnalysis = !status.supported;
    const runtimeApiKey = !skipImageAnalysis && typeof context === 'object' && context.cliproxyBridge
        ? (0, cliproxy_profile_bridge_1.resolveCliproxyBridgeProfile)(context.cliproxyBridge.provider).apiKey
        : '';
    const runtimePath = skipImageAnalysis ? '' : status.runtimePath || '';
    const runtimeBaseUrl = skipImageAnalysis || typeof context !== 'object'
        ? ''
        : context.cliproxyBridge?.currentBaseUrl || '';
    return {
        CCS_IMAGE_ANALYSIS_ENABLED: config.enabled ? '1' : '0',
        CCS_IMAGE_ANALYSIS_TIMEOUT: String(Number(config.timeout) || 60),
        CCS_IMAGE_ANALYSIS_PROVIDER_MODELS: serializeProviderModels(config.provider_models),
        CCS_CURRENT_PROVIDER: status.backendId || '',
        CCS_IMAGE_ANALYSIS_BACKEND_ID: status.backendId || '',
        CCS_IMAGE_ANALYSIS_MODEL: status.model || '',
        CCS_IMAGE_ANALYSIS_RUNTIME_PATH: runtimePath,
        CCS_IMAGE_ANALYSIS_RUNTIME_BASE_URL: runtimeBaseUrl,
        ...(runtimeApiKey ? { CCS_IMAGE_ANALYSIS_RUNTIME_API_KEY: runtimeApiKey } : {}),
        CCS_IMAGE_ANALYSIS_PROMPTS_DIR: (0, hook_installer_1.getPromptsDir)(),
        CCS_IMAGE_ANALYSIS_SKIP: skipImageAnalysis ? '1' : '0',
    };
}
exports.getImageAnalysisHookEnv = getImageAnalysisHookEnv;
/**
 * Overlay execution-specific runtime values onto the baseline image-analysis env.
 * Launch paths use this to pin analysis to the exact provider route and auth
 * token selected for the current session rather than any stale saved values.
 */
function applyImageAnalysisRuntimeOverrides(env, overrides) {
    const nextEnv = { ...env };
    const backendId = overrides.backendId?.trim();
    if (backendId) {
        nextEnv.CCS_CURRENT_PROVIDER = backendId;
        nextEnv.CCS_IMAGE_ANALYSIS_BACKEND_ID = backendId;
    }
    const model = overrides.model?.trim();
    if (model) {
        nextEnv.CCS_IMAGE_ANALYSIS_MODEL = model;
    }
    const runtimePath = overrides.runtimePath?.trim();
    if (runtimePath) {
        nextEnv.CCS_IMAGE_ANALYSIS_RUNTIME_PATH = runtimePath;
    }
    if (overrides.baseUrl !== undefined) {
        nextEnv.CCS_IMAGE_ANALYSIS_RUNTIME_BASE_URL = overrides.baseUrl?.trim() || '';
    }
    if (overrides.apiKey !== undefined) {
        const apiKey = overrides.apiKey?.trim();
        if (apiKey) {
            nextEnv.CCS_IMAGE_ANALYSIS_RUNTIME_API_KEY = apiKey;
        }
        else {
            delete nextEnv.CCS_IMAGE_ANALYSIS_RUNTIME_API_KEY;
        }
    }
    if (overrides.allowSelfSigned !== undefined) {
        nextEnv.CCS_IMAGE_ANALYSIS_RUNTIME_ALLOW_SELF_SIGNED = overrides.allowSelfSigned ? '1' : '0';
    }
    return nextEnv;
}
exports.applyImageAnalysisRuntimeOverrides = applyImageAnalysisRuntimeOverrides;
//# sourceMappingURL=get-image-analysis-hook-env.js.map