import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { NOTICE_KIND } from "./notification-store.js";
import {
	hasCurrentParityWarning,
	writeParityReport,
} from "./uok/parity-report.js";
/**
 * Read the last UOK parity report from <basePath>/.sf/runtime/uok-parity-report.json
 * and surface any divergences or errors via ctx.ui?.notify?.().
 *
 * Never throws — all errors are swallowed so session_start is never blocked.
 */
export async function summarizeParityReport(basePath, ctx, pi) {
	const reportPath = join(basePath, ".sf", "runtime", "uok-parity-report.json");
	if (!existsSync(reportPath)) return;
	let report;
	try {
		report = writeParityReport(basePath);
	} catch {
		try {
			report = JSON.parse(readFileSync(reportPath, "utf-8"));
		} catch {
			// Malformed JSON — silently skip
			return;
		}
	}
	const mismatches = report.criticalMismatches?.length ?? 0;
	const errors = report.statuses?.error ?? 0;
	if (hasCurrentParityWarning(report)) {
		const msg =
			`UOK parity report shows ${mismatches} critical mismatch${mismatches === 1 ? "" : "es"}, ` +
			`${errors} error${errors === 1 ? "" : "s"} since ${report.generatedAt}. ` +
			`Inspect .sf/runtime/uok-parity-report.json.`;
		ctx.ui?.notify?.(msg, "warning", {
			noticeKind: NOTICE_KIND.SYSTEM_NOTICE,
			dedupe_key: "uok-parity-report-current-warning",
		});
	} else {
		const pathCount = Object.keys(report.paths ?? {}).length;
		pi?.logInfo?.(
			"uok-parity",
			`All clean. Last UOK run: ${report.totalEvents} events, ${pathCount} paths.`,
		);
	}
}
