/**
 * Tracks eval finding resolution state.
 *
 * Findings persist as "unresolved" until explicitly fixed or ignored.
 * The eval hook surfaces unresolved findings on every commit (jj describe
 * on jj projects, git commit on git projects).
 */
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { getScorecardQuestions } from "./scorecard-extractor.js";
function getFindingsPath(projectRoot) {
    return join(projectRoot, ".indusk", "eval", "findings.json");
}
function readFindings(projectRoot) {
    const path = getFindingsPath(projectRoot);
    if (!existsSync(path))
        return {};
    try {
        return JSON.parse(readFileSync(path, "utf8"));
    }
    catch {
        return {};
    }
}
function writeFindings(projectRoot, findings) {
    const path = getFindingsPath(projectRoot);
    mkdirSync(dirname(path), { recursive: true });
    writeFileSync(path, `${JSON.stringify(findings, null, 2)}\n`);
}
export function getUnresolvedFindings(projectRoot) {
    const findings = readFindings(projectRoot);
    return Object.entries(findings)
        .filter(([, entry]) => entry.state === "unresolved")
        .map(([key, entry]) => ({ key, ...entry }));
}
export function getAllFindings(projectRoot) {
    const findings = readFindings(projectRoot);
    return Object.entries(findings).map(([key, entry]) => ({ key, ...entry }));
}
export function markFinding(projectRoot, key, state) {
    const findings = readFindings(projectRoot);
    if (!findings[key])
        return false;
    findings[key].state = state;
    writeFindings(projectRoot, findings);
    return true;
}
export function ingestScorecard(projectRoot, scorecard) {
    const findings = readFindings(projectRoot);
    let added = 0;
    // Defensive: the model occasionally returns a scorecard with a missing,
    // null, or non-array `questions` field (it invents its own schema). See
    // `scorecard-extractor.ts` getScorecardQuestions for the central guard.
    const questions = getScorecardQuestions(scorecard);
    for (const q of questions) {
        if (q.answer === "yes")
            continue; // no finding for passing questions
        const key = `${scorecard.changeId}:${q.id}`;
        if (!findings[key]) {
            findings[key] = {
                state: "unresolved",
                questionId: q.id,
                severity: q.severity,
                finding: q.finding,
                changeId: scorecard.changeId,
            };
            added++;
        }
    }
    if (added > 0) {
        writeFindings(projectRoot, findings);
    }
    return added;
}
