/**
 * Pipeline step: Generate PR comment / report from scores.
 *
 * Calls generatePrComment() from pipeline/pr-comment.ts with typed options.
 * No env bridge or process.argv manipulation needed.
 */
import { existsSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "path";
import { assoc, } from "../../_vendor/ailf-core/index.js";
import { emitFileContents } from "../../artifact-capture/emit-file.js";
import { checkScoreSummaryValid } from "../../pipeline/checks.js";
import { generatePrComment } from "../../pipeline/pr-comment.js";
export class ReportStep {
    name = "report";
    check() {
        return [];
    }
    async execute(ctx) {
        const start = Date.now();
        // Precondition: score summary exists (intermediate files stay in rootDir)
        const summaryIssues = checkScoreSummaryValid(ctx.config.rootDir);
        const summaryErrors = summaryIssues.filter((i) => i.severity === "error");
        if (summaryErrors.length > 0) {
            return {
                durationMs: Date.now() - start,
                error: `Score summary missing: ${summaryErrors.map((e) => e.message).join("; ")}`,
                status: "failed",
            };
        }
        // User-facing output: --output flag wins, else outputDir
        const resolvedOutput = ctx.config.outputPath ?? resolve(ctx.config.outputDir, "pr-comment.md");
        // Ensure outputDir exists before writing (it may be a custom --output-dir
        // that hasn't been created yet — writePipelineResult runs after the
        // orchestrator returns, so we can't rely on it).
        mkdirSync(dirname(resolvedOutput), { recursive: true });
        try {
            generatePrComment({
                outputPath: resolvedOutput,
                promptfooUrl: ctx.config.promptfooUrl,
                rootDir: ctx.config.rootDir,
            });
        }
        catch (err) {
            return {
                durationMs: Date.now() - start,
                error: `pr-comment failed: ${err instanceof Error ? err.message : String(err)}`,
                status: "failed",
            };
        }
        // W0050 — captureFile → emitFileContents. Both are run-scoped bulk
        // artifacts; the writer handles redaction + excluded-types gating.
        if (existsSync(resolvedOutput)) {
            await emitFileContents(ctx.artifactWriter, "prComment", assoc(ctx), resolvedOutput);
        }
        const pipelineResultPath = resolve(ctx.config.outputDir, "pipeline-result.json");
        if (existsSync(pipelineResultPath)) {
            await emitFileContents(ctx.artifactWriter, "pipelineResult", assoc(ctx), pipelineResultPath);
        }
        return {
            durationMs: Date.now() - start,
            status: "success",
            summary: `Report written to ${resolvedOutput}`,
        };
    }
}
