import { spawn } from "node:child_process";
import { isNotFound } from "@poe-code/config-mutations";
import { resolveCliSettings, resolveIsolatedEnvDetails } from "./isolated-env.js";
import { buildArgsWithMergedSettings } from "../utils/cli-settings-merge.js";
export async function isolatedEnvRunner(input) {
    const details = await resolveIsolatedEnvDetails(input.env, input.isolated, input.providerName, input.activeProvider);
    let args = input.argv.slice(2);
    if (input.isolated.requiresConfig !== false) {
        const hasConfig = await configExists(input.fs, details.configProbePath);
        if (!hasConfig) {
            throw new Error(`${input.providerName} is not configured. Run 'poe-code login' or 'poe-code configure ${input.providerName}'.`);
        }
    }
    // Merge CLI settings if provider defines them
    if (input.isolated.cliSettings) {
        const resolvedSettings = await resolveCliSettings(input.isolated.cliSettings, input.env, input.activeProvider);
        args = buildArgsWithMergedSettings(args, resolvedSettings);
    }
    const child = spawn(details.agentBinary, args, {
        stdio: "inherit",
        env: {
            ...process.env,
            ...details.env
        }
    });
    return await new Promise((_, reject) => {
        child.on("error", (error) => {
            reject(error);
        });
        child.on("close", (code, signal) => {
            process.exit(code ?? (signal === null ? 0 : 1));
        });
    });
}
async function configExists(fs, filePath) {
    if (!fs) {
        return true;
    }
    try {
        await fs.stat(filePath);
        return true;
    }
    catch (error) {
        if (isNotFound(error)) {
            return false;
        }
        throw error;
    }
}
//# sourceMappingURL=isolated-env-runner.js.map