import { randomUUID } from "node:crypto";
import { cpSync, existsSync, readFileSync } from "node:fs";
import { join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import dotenv from "dotenv";
import { logger } from "../common/logger.js";
import { ConsoleOutput, printCriticalFailureToConsoleAndExit, printDiagnosticsToConsole, printResultToConsoleAndExitGracefully, } from "../common/output.js";
import { handleRuntimeStdio } from "../common/worker-output.js";
export async function compile(argv) {
    const sourceDirectory = resolve(join(relative(process.cwd(), argv.dir)));
    const zuploRuntimePath = new URL("../../node_modules/@zuplo/runtime", import.meta.url);
    if (existsSync(zuploRuntimePath)) {
        cpSync(zuploRuntimePath, join(sourceDirectory, "node_modules/@zuplo/runtime"), {
            recursive: true,
            dereference: true,
        });
    }
    process.env.GLOBAL_MODULE_LOCATION = fileURLToPath(new URL("../../node_modules", import.meta.url));
    let envZuplo = {};
    const envZuploFile = join(sourceDirectory, ".env.zuplo");
    if (existsSync(envZuploFile)) {
        const contents = readFileSync(envZuploFile);
        envZuplo = dotenv.parse(contents);
    }
    const core = await import("@zuplo/core/cli");
    const zupPort = argv.port;
    const buildId = argv["build-id"] || randomUUID();
    try {
        await core.compileWorkerdServer({
            buildId,
            output: new ConsoleOutput(),
            sourceDirectory,
            bundledDir: argv["bundled-dir"],
            port: zupPort,
            binaryName: argv["binary-name"],
            publicZuploEnvironmentVariables: envZuplo
                ? {
                    ZUPLO_ACCOUNT_NAME: envZuplo.ZUPLO_ACCOUNT_NAME,
                    ZUPLO_PROJECT_NAME: envZuplo.ZUPLO_PROJECT_NAME,
                    ZUPLO_ENVIRONMENT_TYPE: envZuplo.ZUPLO_ENVIRONMENT_TYPE,
                }
                :
                    undefined,
            logger,
            handleRuntimeStdio,
        });
        printDiagnosticsToConsole("📦 Compiled a self-contained zup binary");
        await printResultToConsoleAndExitGracefully(`The binary is available at ${sourceDirectory}/dist/${argv["binary-name"]}`);
    }
    catch (err) {
        printDiagnosticsToConsole(err.message);
        await printCriticalFailureToConsoleAndExit("Failed to compile the zup binary");
    }
}
//# sourceMappingURL=handler.js.map