/**
 * pipeline/pr-comment.ts — Generate a markdown PR comment from
 * `results/latest/score-summary.json` (and an optional comparison-report).
 *
 * Thin wrapper around `@sanity/ailf-core`'s unified renderer (W0150).
 * Reads the local JSON files, applies legacy-field normalization on the
 * scores, builds a `RenderableReport` envelope (so the CLI's
 * `--promptfoo-url` flag flows through `provenance.promptfooUrls[0]`),
 * then delegates rendering.
 *
 * All functions accept `rootDir` as a parameter — no module-level
 * constants. No `process.argv` parsing. No env-var fallbacks.
 */
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import { reportToMarkdown } from "../_vendor/ailf-core/index.js";
export function generatePrComment(options) {
    const { outputPath, promptfooUrl, rootDir } = options;
    const summaryPath = resolve(rootDir, "results/latest/score-summary.json");
    const comparisonPath = resolve(rootDir, "results/latest/comparison-report.json");
    const raw = readFileSync(summaryPath, "utf-8");
    const parsed = JSON.parse(raw);
    const summary = {
        ...parsed,
        scores: parsed.scores.map((s) => normalizeScore(s)),
    };
    let comparison;
    if (existsSync(comparisonPath)) {
        try {
            comparison = JSON.parse(readFileSync(comparisonPath, "utf-8"));
        }
        catch {
            // Non-fatal — comparison report is optional.
        }
    }
    const report = scoreSummaryToRenderableReport(summary, comparison, {
        promptfooUrl,
    });
    const markdown = reportToMarkdown(report);
    if (outputPath) {
        writeFileSync(outputPath, markdown);
    }
    else {
        process.stdout.write(markdown);
    }
}
/**
 * Adapter: build a {@link RenderableReport} from the in-memory pipeline
 * artifacts. Exposed for the cross-renderer byte-equality contract test.
 */
export function scoreSummaryToRenderableReport(summary, comparison, options = {}) {
    const provenance = {};
    if (options.promptfooUrl) {
        provenance.promptfooUrls = [{ mode: "unknown", url: options.promptfooUrl }];
    }
    return {
        completedAt: summary.timestamp,
        summary,
        comparison,
        provenance,
    };
}
// ---------------------------------------------------------------------------
// Legacy field normalization — pre-W0051 score summaries used different
// field names. Keep these here so old cached score-summary.json files
// still render correctly.
// ---------------------------------------------------------------------------
function normalizeScore(s) {
    const ceiling = s.ceilingScore ??
        s.withDocsScore ??
        s.totalScore ??
        0;
    const floor = s.floorScore ??
        s.withoutDocsScore ??
        0;
    const lift = s.docLift ??
        s.liftFromDocs ??
        ceiling - floor;
    return {
        ...s,
        ceilingScore: ceiling,
        docLift: lift,
        docQualityGap: s.docQualityGap ?? 100 - ceiling,
        floorScore: floor,
        negativeDocLift: s.negativeDocLift ?? lift < 0,
    };
}
