"use strict";
/**
 * Proxy Target Resolver
 *
 * Determines whether CLIProxyAPI requests should go to local or remote
 * based on unified config. Used by stats-fetcher, auth-routes, and UI.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildManagementHeaders = exports.buildProxyHeaders = exports.buildProxyUrl = exports.getProxyTarget = void 0;
const port_manager_1 = require("../config/port-manager");
const proxy_config_resolver_1 = require("./proxy-config-resolver");
const auth_token_manager_1 = require("../auth/auth-token-manager");
const config_loader_facade_1 = require("../../config/config-loader-facade");
/**
 * Load cliproxy_server configuration from unified config.
 * Returns undefined if not configured.
 */
function loadCliproxyServerConfig() {
    const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
    return config.cliproxy_server;
}
/**
 * Get the current CLIProxyAPI target based on unified config.
 * Returns remote server config if enabled, otherwise localhost.
 */
function getProxyTarget() {
    const config = loadCliproxyServerConfig();
    const envConfig = (0, proxy_config_resolver_1.getProxyEnvVars)();
    if (config?.remote?.enabled && config.remote?.host) {
        // Normalize protocol (handles case sensitivity and invalid values)
        const protocol = (0, port_manager_1.normalizeProtocol)(config.remote.protocol);
        // Validate port (returns undefined for invalid, triggering default)
        const validatedPort = (0, port_manager_1.validateRemotePort)(config.remote.port);
        const port = validatedPort ?? (0, port_manager_1.getRemoteDefaultPort)(protocol);
        return {
            host: config.remote.host,
            port,
            protocol,
            authToken: config.remote.auth_token || undefined, // Empty string -> undefined
            managementKey: config.remote.management_key || undefined, // Empty string -> undefined
            allowSelfSigned: envConfig.allowSelfSigned,
            isRemote: true,
        };
    }
    const localPort = (0, port_manager_1.validatePort)(config?.local?.port ?? port_manager_1.CLIPROXY_DEFAULT_PORT);
    return {
        host: '127.0.0.1',
        port: localPort,
        protocol: 'http',
        isRemote: false,
    };
}
exports.getProxyTarget = getProxyTarget;
/**
 * Build URL for proxy endpoint
 * @param target Resolved proxy target
 * @param path Endpoint path (e.g., '/v0/management/usage')
 */
function buildProxyUrl(target, path) {
    // Normalize path to ensure leading slash
    const normalizedPath = path.startsWith('/') ? path : `/${path}`;
    return `${target.protocol}://${target.host}:${target.port}${normalizedPath}`;
}
exports.buildProxyUrl = buildProxyUrl;
/**
 * Build request headers for proxy requests
 * Handles optional auth token - only adds Authorization header if token is set.
 *
 * @param target Resolved proxy target
 * @param additionalHeaders Extra headers to merge
 */
function buildProxyHeaders(target, additionalHeaders = {}) {
    const headers = {
        Accept: 'application/json',
        ...additionalHeaders,
    };
    // Only add auth header if token is configured
    if (target.authToken) {
        headers['Authorization'] = `Bearer ${target.authToken}`;
    }
    return headers;
}
exports.buildProxyHeaders = buildProxyHeaders;
/**
 * Build request headers for management API endpoints (/v0/management/*).
 * For remote targets: uses management_key, falls back to authToken.
 * For local targets: uses the effective management secret from CCS config.
 *
 * @param target Resolved proxy target
 * @param additionalHeaders Extra headers to merge
 */
function buildManagementHeaders(target, additionalHeaders = {}) {
    const headers = {
        Accept: 'application/json',
        ...additionalHeaders,
    };
    // Remote: use configured management key or auth token
    // Local: use CCS management secret (default: 'ccs')
    const authKey = target.isRemote
        ? (target.managementKey ?? target.authToken)
        : (0, auth_token_manager_1.getEffectiveManagementSecret)();
    if (authKey) {
        headers['Authorization'] = `Bearer ${authKey}`;
    }
    return headers;
}
exports.buildManagementHeaders = buildManagementHeaders;
//# sourceMappingURL=proxy-target-resolver.js.map