/**
 * remote-results.ts — Write output artifacts from a remote evaluation.
 *
 * Produces the same file layout as local mode so downstream tools
 * (workflow PR comments, score comparison, baseline save) work unchanged:
 *
 *   <outputDir>/score-summary.json  — scores by area + overall
 *   <outputDir>/report.md           — rendered markdown report
 *   <outputDir>/job-metadata.json   — job ID, timing, API URL
 *
 * @see packages/eval/src/commands/remote-pipeline.ts — caller
 */
import { mkdirSync, writeFileSync } from "fs";
import { resolve } from "path";
import { resolveReportUrl } from "../sinks/slack/dashboard-links.js";
/**
 * Fetch report artifacts from the API and write them to disk.
 *
 * Writes:
 * - `<outputDir>/score-summary.json` — score data from job response
 * - `<outputDir>/report.md` — full markdown report (if reportId present)
 * - `<outputDir>/job-metadata.json` — job tracking info
 * - `--output` path — markdown report (if specified)
 *
 * Returns an outcome the caller uses to choose an exit code: a `completed`
 * job that carries `job.error` is treated as a *degraded* completion (a
 * configured optional step failed end-to-end; see DOC-2121 RC-3) and the
 * caller should exit non-zero so external `--remote` consumers don't read
 * a clean completion as success.
 */
export async function writeRemoteResults(client, job, options) {
    const resultsDir = options.outputDir;
    mkdirSync(resultsDir, { recursive: true });
    // 1. Write score summary
    const scoreSummary = buildScoreSummary(job);
    writeFileSync(resolve(resultsDir, "score-summary.json"), JSON.stringify(scoreSummary, null, 2));
    // 2. Fetch and write markdown report
    let reportWritten = false;
    if (job.reportId) {
        try {
            const markdown = await client.getReportMarkdown(job.reportId);
            writeFileSync(resolve(resultsDir, "report.md"), markdown);
            reportWritten = true;
            // Also write to --output path if specified
            if (options.outputPath) {
                writeFileSync(options.outputPath, markdown);
            }
        }
        catch (err) {
            console.warn(`  ⚠️  Could not fetch report: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    // 3. Write job metadata
    writeFileSync(resolve(resultsDir, "job-metadata.json"), JSON.stringify({
        jobId: job.jobId,
        status: job.status,
        startedAt: job.startedAt ?? null,
        completedAt: job.completedAt ?? null,
        reportId: job.reportId ?? null,
        reportUrl: job.reportUrl ?? null,
        execution: job.execution ?? null,
        error: job.error ?? null,
        apiUrl: options.apiUrl,
    }, null, 2));
    // 4. Print summary. A completed job with `job.error` set means a
    // configured optional step failed end-to-end — print the diagnostic
    // and signal the caller to exit non-zero.
    const degraded = Boolean(job.error);
    console.log("");
    if (degraded) {
        console.log(`⚠️  Evaluation completed with errors`);
    }
    else {
        console.log(`✅ Evaluation completed`);
    }
    console.log(`   📊 Results: ${resolve(resultsDir, "score-summary.json")}`);
    if (reportWritten) {
        console.log(`   📝 Report:  ${resolve(resultsDir, "report.md")}`);
    }
    if (options.outputPath && reportWritten) {
        console.log(`   📄 Output:  ${options.outputPath}`);
    }
    // Dashboard deep-link to the published report. `job.reportUrl` from the API
    // is a relative API path (/v1/reports/<id>), not a clickable page — build
    // the real dashboard URL from the report id instead.
    const dashboardUrl = resolveReportUrl(job.reportId);
    if (dashboardUrl) {
        console.log(`   🔗 Dashboard: ${dashboardUrl}`);
    }
    console.log(`   🏷️  Job ID:  ${job.jobId}`);
    if (job.error) {
        console.error("");
        console.error(`   ❌ Step "${job.error.step ?? "<unknown>"}" failed: ${job.error.message}`);
        if (!job.reportId) {
            console.error("   No report was published. See the API gateway run page for details.");
        }
    }
    return { degraded };
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
/**
 * Build a score summary object from the job response.
 *
 * The job response may contain a full scoreSummary (if the API includes it)
 * or just minimal data. We build a structure that's compatible with the
 * local pipeline's score-summary.json format.
 */
function buildScoreSummary(job) {
    // The job response from the API may include inline score data in the
    // future. For now, we store what we have — the job metadata — so
    // downstream tools can at least read the file and know a remote eval
    // completed.
    return {
        _remote: true,
        jobId: job.jobId,
        status: job.status,
        reportId: job.reportId ?? null,
        completedAt: job.completedAt ?? null,
    };
}
