/**
 * Judgment log — records agent decision-making during autonomous mode.
 *
 * JudgmentEntries accumulate in the SQLite judgments table (schema v40+).
 * Storage: sf.db judgments table — DB-first, no file fallback.
 *
 * The tool `log_decision` (registered in dynamic-tools.ts or equivalent)
 * calls appendJudgment(). readJudgmentLog() is used by the compounding step.
 */
import { mkdirSync } from "node:fs";
import { join } from "node:path";
import { sfRoot } from "./paths.js";
import { getJudgmentsForUnit, insertJudgment, openDatabase } from "./sf-db.js";

const JUDGMENT_LOG_SCHEMA_VERSION = 1;

/**
 * Append a single judgment entry to the judgment log.
 * Writes to the SF SQLite DB. Non-fatal on DB failure — the agent loop must not be disrupted.
 */
export function appendJudgment(basePath, entry) {
	const full = {
		schemaVersion: JUDGMENT_LOG_SCHEMA_VERSION,
		ts: new Date().toISOString(),
		...entry,
	};

	try {
		ensureJudgmentDb(basePath);
		insertJudgment(full);
	} catch {
		// Non-fatal — judgment logging must never break the agent loop
	}
}

/**
 * Read judgment log entries, optionally filtered by unitId prefix.
 *
 * @param basePath - project root
 * @param unitId - optional filter; when provided, only entries whose unitId
 *   starts with this value are returned (e.g. "M001" returns all M001 entries)
 */
export function readJudgmentLog(basePath, unitId) {
	try {
		ensureJudgmentDb(basePath);
		const rows = getJudgmentsForUnit(unitId ?? "", 1000);
		return rows.map((r) => ({
			schemaVersion: JUDGMENT_LOG_SCHEMA_VERSION,
			...r,
			alternatives: r.alternatives,
		}));
	} catch {
		return [];
	}
}

function ensureJudgmentDb(basePath) {
	const dir = sfRoot(basePath);
	mkdirSync(dir, { recursive: true });
	if (!openDatabase(join(dir, "sf.db"))) {
		throw new Error("SF judgment database unavailable");
	}
}
