/**
 * Analyse-verify diagnostics — builds + writes the `analyse-quality.json`
 * sidecar (mirror of realize's `realize-quality.json`). Pure builder split
 * from the fs writer so the shape is unit-testable without disk.
 */
import { writeFileSync } from 'fs';
import { join } from 'path';
/** Map a stub `yamlPath` → its { ownerName, actionName } via provenance. */
function stubIndex(prov) {
    const idx = new Map();
    for (const s of prov.actionStubs) {
        idx.set(s.yamlPath, { ownerName: s.ownerName, actionName: s.actionName });
    }
    return idx;
}
/** Build the sidecar object. `ranAt` is supplied by the caller (engines runtime
 *  has Date; we keep this builder pure for testing). */
export function buildAnalyseQualitySidecar(opts) {
    const { initialFindings, residualFindings, skeletonProvenance, refired, notes, ranAt } = opts;
    const idx = stubIndex(skeletonProvenance);
    const residualKeys = new Set(residualFindings.map((f) => `${f.code}::${f.stubPath}`));
    const byOwner = {};
    const findingsByCode = {};
    for (const f of initialFindings) {
        const meta = idx.get(f.stubPath);
        const ownerName = meta?.ownerName ?? '__unmapped__';
        const actionName = meta?.actionName ?? f.stubPath;
        if (!byOwner[ownerName])
            byOwner[ownerName] = { ownerName, findings: [] };
        byOwner[ownerName].findings.push({
            code: f.code,
            stubPath: f.stubPath,
            actionName,
            severity: f.severity,
            message: f.message,
            residual: residualKeys.has(`${f.code}::${f.stubPath}`),
        });
        findingsByCode[f.code] = (findingsByCode[f.code] ?? 0) + 1;
    }
    return {
        schemaVersion: '1.0',
        ranAt,
        totals: {
            findings: initialFindings.length,
            findingsByCode,
            ownersWithFindings: Object.keys(byOwner).length,
            residual: residualFindings.length,
            refired,
        },
        byOwner,
        notes,
    };
}
/** Write the sidecar to `<outputDir>/analyse-quality.json`. Best-effort. */
export function writeAnalyseQuality(outputDir, sidecar) {
    const path = join(outputDir, 'analyse-quality.json');
    writeFileSync(path, JSON.stringify(sidecar, null, 2));
    return path;
}
/** CLI summary line — `null` when there's nothing to report. */
export function formatAnalyseQualityLine(sidecar) {
    const { findings, ownersWithFindings, residual } = sidecar.totals;
    if (findings === 0)
        return null;
    const resolved = findings - residual;
    return (`⚠ analyse-quality: ${findings} finding(s) across ${ownersWithFindings} owner(s) ` +
        `(${resolved} resolved, ${residual} residual — see analyse-quality.json)`);
}
//# sourceMappingURL=diagnostics.js.map