/**
 * Adapter: Run evaluation via Promptfoo CLI subprocess.
 *
 * This wraps the current execSync-based eval execution behind the
 * EvalRunner port interface, enabling mock-based testing of the
 * pipeline orchestrator.
 */
import { execSync } from "child_process";
import { existsSync, readFileSync } from "fs";
import { resolve } from "path";
export class PromptfooEvalAdapter {
    rootDir;
    constructor(rootDir) {
        this.rootDir = rootDir;
    }
    async run(config) {
        const start = Date.now();
        // Resolve .env path — monorepo root (../../.env) or caller's cwd (.env)
        const monorepoEnv = resolve(this.rootDir, "..", "..", ".env");
        const callerEnv = resolve(process.env.AILF_CALLER_CWD ?? process.cwd(), ".env");
        const envFile = existsSync(monorepoEnv) ? monorepoEnv : callerEnv;
        const dotenvPrefix = existsSync(envFile) ? `dotenv -e ${envFile} -o --` : "";
        const parts = [
            dotenvPrefix,
            "npx promptfoo eval",
            `-c ${config.configPath}`,
            config.filterFlags ?? "",
            config.concurrency ? `--max-concurrency ${config.concurrency}` : "",
        ].filter(Boolean);
        const cmd = parts.join(" ");
        try {
            execSync(cmd, {
                cwd: this.rootDir,
                env: { ...process.env, ...config.env },
                stdio: "inherit",
                ...(config.maxDurationMs ? { timeout: config.maxDurationMs } : {}),
            });
            return {
                durationMs: Date.now() - start,
                status: "success",
                summary: `Evaluation complete (${config.configPath})`,
            };
        }
        catch (err) {
            const isTimeout = err instanceof Error &&
                "killed" in err &&
                err.killed === true;
            return {
                durationMs: Date.now() - start,
                error: isTimeout
                    ? `Eval subprocess killed after ${config.maxDurationMs}ms time budget`
                    : `Promptfoo evaluation failed: ${config.configPath}`,
                status: "failed",
            };
        }
    }
    extractShareUrl(outputPath) {
        if (!existsSync(outputPath))
            return undefined;
        try {
            const raw = readFileSync(outputPath, "utf-8");
            const data = JSON.parse(raw);
            return data.shareableUrl ?? undefined;
        }
        catch {
            return undefined;
        }
    }
}
