// engine/spec-audit/report-writer.ts — SPEC-744
// Generates the prioritised markdown drift report and appends pending review entries.
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { join, dirname } from 'node:path';
import { existsSync } from 'node:fs';
import { atomicWriteFile } from '../safety/atomic-write-file.js';
import { hashProjectPath, projectDataDir } from '../../storage/base-store.js';
// ---------------------------------------------------------------------------
// Markdown report
// ---------------------------------------------------------------------------
export function buildMarkdownReport(report) {
    const p0 = report.findings.filter((f) => f.priority === 'P0');
    const p1 = report.findings.filter((f) => f.priority === 'P1');
    const p2 = report.findings.filter((f) => f.priority === 'P2');
    const lines = [
        `# Spec Drift Audit — ${report.generatedAt}`,
        ``,
        `## Summary`,
        ``,
        `| Priority | Count |`,
        `|----------|-------|`,
        `| P0 — broken refs | ${p0.length} |`,
        `| P1 — signature drift | ${p1.length} |`,
        `| P2 — doc drift | ${p2.length} |`,
        `| Total scanned | ${report.scanned} |`,
        `| Skipped (superseded) | ${report.skippedSuperseded.length} |`,
        ``,
        `Budget consumed: $${report.budgetUsedUsd.toFixed(4)} / $${(report.budgetUsedUsd + report.budgetRemainingUsd).toFixed(2)} remaining`,
        ``,
    ];
    if (report.skippedSuperseded.length > 0) {
        lines.push(`## Skipped (superseded)`);
        lines.push(``);
        for (const s of report.skippedSuperseded) {
            lines.push(`- ${s}`);
        }
        lines.push(``);
    }
    function appendSection(title, items) {
        lines.push(`## ${title}`);
        lines.push(``);
        if (items.length === 0) {
            lines.push('_No issues found._');
        }
        else {
            for (const f of items) {
                lines.push(`- **${f.specId}** (path: \`${f.path}\`, tier-${f.tier}): ${f.reason}`);
                lines.push(`  > ${f.evidence}`);
            }
        }
        lines.push(``);
    }
    appendSection('P0 — broken refs', p0);
    appendSection('P1 — signature drift', p1);
    appendSection('P2 — doc drift', p2);
    return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Write report atomically
// ---------------------------------------------------------------------------
export async function writeAuditReport(report, _projectRoot) {
    const dir = dirname(report.reportPath);
    await mkdir(dir, { recursive: true });
    const content = buildMarkdownReport(report);
    await atomicWriteFile(report.reportPath, content);
}
// ---------------------------------------------------------------------------
// Append to pending.json
// ---------------------------------------------------------------------------
export async function appendDriftReviewToPending(entry, projectRoot) {
    const pendingPath = join(projectDataDir(hashProjectPath(projectRoot)), 'pending.json');
    let existing = [];
    if (existsSync(pendingPath)) {
        try {
            const raw = await readFile(pendingPath, 'utf-8');
            const parsed = JSON.parse(raw);
            existing = Array.isArray(parsed) ? parsed : [];
        }
        catch {
            existing = [];
        }
    }
    existing.push(entry);
    await mkdir(dirname(pendingPath), { recursive: true });
    await writeFile(pendingPath, JSON.stringify(existing, null, 2), 'utf-8');
}
//# sourceMappingURL=report-writer.js.map