import { spawn } from "child_process";
import { getLogger } from "../../../util/logger.js";
import { FileTransformer } from "../shared.js";
export class ApiBuilderTypeScriptError extends Error {
    constructor(message) {
        super(message);
        this.name = "ApiBuilderTypeScriptError";
        Object.setPrototypeOf(this, ApiBuilderTypeScriptError.prototype);
    }
}
export class ApiBuilderTransformationError extends Error {
    constructor(message) {
        super(message);
        this.name = "ApiBuilderTransformationError";
        Object.setPrototypeOf(this, ApiBuilderTransformationError.prototype);
    }
}
export class ApiBuilderTransformer extends FileTransformer {
    templateRenderer;
    constructor(src, dest, templateRenderer) {
        super(src, dest);
        this.templateRenderer = templateRenderer;
    }
    async renderTemplate() {
        return this.templateRenderer.renderTemplate("api-builder-to-yaml");
    }
    /**
     * Override to provide additional environment variables for the evaluation process.
     * These are passed to the node evaluator script.
     */
    getEvalEnv() {
        return {};
    }
    runEvaluation(cwd) {
        return new Promise((resolve, reject) => {
            const logger = getLogger();
            logger.debug(`[ai-service] Evaluating in ${cwd}`);
            const tsc = spawn("npx", ["tsc", "--noEmitOnError", "false", "--noErrorTruncation", "true"], { cwd, shell: true });
            const outputLines = [];
            tsc.stdout.on("data", (data) => {
                logger.info("[ai-service] tsc stdout", data.toString());
                outputLines.push(data.toString());
            });
            tsc.on("close", (code) => {
                if (code !== 0) {
                    return reject(new ApiBuilderTypeScriptError(outputLines.join("\n")));
                }
                // Merge additional environment variables from subclass
                const evalEnv = {
                    ...process.env,
                    ...this.getEvalEnv(),
                };
                const evaluator = spawn("node", ["--import", "./bootstrap.mjs", this.evalScript], { cwd, shell: true, env: evalEnv });
                let outputData = "";
                let errorData = "";
                evaluator.stdout.on("data", (data) => {
                    outputData += data.toString();
                });
                evaluator.stderr.on("data", (data) => {
                    errorData += data.toString();
                });
                evaluator.on("close", (code) => {
                    if (code !== 0 || errorData) {
                        return reject(new ApiBuilderTransformationError(`Evaluation process exited with code ${code}: ${errorData}`));
                    }
                    try {
                        const result = JSON.parse(outputData);
                        resolve(result);
                    }
                    catch (error) {
                        reject(new Error(`Failed to parse evaluation output: ${error}`));
                    }
                });
            });
        });
    }
}
//# sourceMappingURL=shared.js.map