import { TypescriptPreprocessor } from "../preprocessors/typescriptPreprocessor.js";
import { buildCompilationUnit } from "../compilationUnit.js";
import { TypeScriptBuilder } from "./typescriptBuilder.js";
import { printTs } from "../ir/prettyPrint.js";
/**
 * Project a `CompiledClosure` to a single module's per-module init view.
 * Used by both compile entry points (`lib/cli/commands.ts` and
 * `lib/compiler/compile.ts`) — they each build the closure once at the
 * outer call, then call this helper for every per-file `generateTypeScript`.
 */
export function initPlanForModule(closure, moduleId) {
    const plan = closure.plans[moduleId];
    return {
        registryModuleId: moduleId,
        staticLocalOrder: plan?.static.localOrder ?? [],
        staticAwaitModules: (plan?.static.awaitModules ?? []).map((m) => ({
            // `localImport` is currently unused at codegen time — the runtime
            // lookup keys off `sourceModuleId` directly — but we keep the
            // field for future use (e.g., emitting `export ... from` aliases
            // in the centralized-init successor work).
            localImport: m,
            sourceModuleId: m,
        })),
        globalLocalOrder: plan?.global.localOrder ?? [],
        globalAwaitModules: (plan?.global.awaitModules ?? []).map((m) => ({
            localImport: m,
            sourceModuleId: m,
        })),
        resolveImportedName: (localName) => closure.resolver.resolve(localName, moduleId),
    };
}
export function generateTypeScript(program, config, info, moduleId, outputFile, initPlan) {
    if (!moduleId) {
        throw new Error("moduleId is required for generateTypeScript");
    }
    const compilationUnit = info ?? buildCompilationUnit(program);
    const preprocessor = new TypescriptPreprocessor(program, config, compilationUnit);
    const preprocessedProgram = preprocessor.preprocess();
    const builder = new TypeScriptBuilder(config, compilationUnit, moduleId, outputFile, initPlan);
    const ir = builder.build(preprocessedProgram);
    return printTs(ir);
}
