/**
 * Rewrite localhost / 127.0.0.1 URLs to host.docker.internal so the Docker
 * executor container can reach services running on the host machine.
 *
 * Only applied when NOT using host networking (bridge mode), because in bridge
 * mode the container's localhost is its own loopback, not the host's.
 * host.docker.internal is mapped via ExtraHosts in TestExecutionService.
 */
export function rewriteLocalhostForDocker(url) {
    return url.replace(/^(https?:\/\/)(localhost|127\.0\.0\.1)([:/?#]|$)/, (_, scheme, _host, rest) => `${scheme}host.docker.internal${rest}`);
}
/**
 * Build the environment variable array for the Docker executor container.
 */
export function buildContainerEnv(options, saveStoragePath, hostEnv = process.env) {
    const env = [
        `SKYRAMP_TEST_TOKEN=${options.token || ""}`,
        "SKYRAMP_IN_DOCKER=true",
    ];
    // Skyramp-generated tests are standalone HTTP tests that never need host repo
    // conftest.py files or pytest configuration. --noconftest prevents loading any
    // conftest in the test directory tree (avoids missing deps like boto3, django).
    // -c /dev/null overrides all config file discovery (pyproject.toml, pytest.ini,
    // setup.cfg, tox.ini) so user-repo plugins (e.g. pytest-timeout) not installed
    // in the executor container don't cause INTERNALERROR at collection time.
    if (options.language === "python") {
        env.push(`PYTEST_ADDOPTS=--noconftest -c /dev/null`);
    }
    if (saveStoragePath) {
        env.push(`PLAYWRIGHT_SAVE_STORAGE_PATH=${saveStoragePath}`);
    }
    // Forward base URL env vars so generated tests can resolve URLs inside the container.
    // In bridge networking (the default), localhost inside the container is the container's
    // own loopback — not the host's.  Rewrite to host.docker.internal so the container
    // can reach host-bound services.  Skip the rewrite in host networking mode where
    // localhost already resolves to the host.
    const shouldRewrite = !options.useHostNetwork;
    for (const [key, val] of Object.entries(hostEnv)) {
        if ((key === "SKYRAMP_TEST_BASE_URL" ||
            key.startsWith("SKYRAMP_TEST_SERVICE_URL_")) &&
            val) {
            env.push(`${key}=${shouldRewrite ? rewriteLocalhostForDocker(val) : val}`);
        }
    }
    if (hostEnv.SKYRAMP_DEBUG) {
        env.push(`SKYRAMP_DEBUG=${hostEnv.SKYRAMP_DEBUG}`);
    }
    if (hostEnv.API_KEY) {
        env.push(`API_KEY=${hostEnv.API_KEY}`);
    }
    return env;
}
