"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initializeProxy = initializeProxy;
exports.disableProxy = disableProxy;
exports.isProxyConfigured = isProxyConfigured;
exports.getProxyInfo = getProxyInfo;
const undici_1 = require("undici");
const logger_1 = require("./logger");
const logger = logger_1.Logger.getInstance("proxy.fetch");
let originalDispatcher = null;
let proxyInitialized = false;
/**
 * Initialize proxy support for native fetch
 * Call this once at application startup to enable proxy support globally.
 *
 * EnvHttpProxyAgent automatically reads and respects:
 * - HTTP_PROXY / http_proxy
 * - HTTPS_PROXY / https_proxy
 * - NO_PROXY / no_proxy
 */
function initializeProxy() {
    if (proxyInitialized) {
        return;
    }
    if (!isProxyConfigured()) {
        logger.debug("No proxy configured in environment variables");
        proxyInitialized = true;
        return;
    }
    // Store original dispatcher so we can restore it if needed
    originalDispatcher = (0, undici_1.getGlobalDispatcher)();
    // EnvHttpProxyAgent automatically reads HTTP_PROXY, HTTPS_PROXY, NO_PROXY from environment
    const proxyAgent = new undici_1.EnvHttpProxyAgent();
    (0, undici_1.setGlobalDispatcher)(proxyAgent);
    const proxyInfo = getProxyInfo();
    logger.debug(`Proxy initialized - HTTP: ${proxyInfo.httpProxy || "none"}, HTTPS: ${proxyInfo.httpsProxy || "none"}, NO_PROXY: ${proxyInfo.noProxy || "none"}`);
    proxyInitialized = true;
}
/**
 * Restore original dispatcher (disable proxy)
 */
function disableProxy() {
    if (originalDispatcher) {
        (0, undici_1.setGlobalDispatcher)(originalDispatcher);
        originalDispatcher = null;
    }
    proxyInitialized = false;
}
/**
 * Check if a proxy is configured in environment variables
 */
function isProxyConfigured() {
    return !!(process.env["HTTP_PROXY"] ||
        process.env["HTTPS_PROXY"] ||
        process.env["http_proxy"] ||
        process.env["https_proxy"]);
}
/**
 * Get configured proxy information for logging/debugging
 */
function getProxyInfo() {
    return {
        httpProxy: process.env["HTTP_PROXY"] || process.env["http_proxy"],
        httpsProxy: process.env["HTTPS_PROXY"] || process.env["https_proxy"],
        noProxy: process.env["NO_PROXY"] || process.env["no_proxy"],
    };
}
//# sourceMappingURL=proxy.js.map