/**
 * judgment-log-db.test.mjs — DB-backed judgment log coverage.
 *
 * Purpose: prove agent judgments are persisted in the project SQLite DB and
 * do not leak across projects when the process switches roots.
 */
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "vitest";
import { appendJudgment, readJudgmentLog } from "../judgment-log.js";
import { closeDatabase, getJudgmentsForUnit, openDatabase } from "../sf-db.js";

const tmpRoots = [];

afterEach(() => {
	closeDatabase();
	for (const root of tmpRoots.splice(0)) {
		rmSync(root, { recursive: true, force: true });
	}
});

function makeProject() {
	const root = mkdtempSync(join(tmpdir(), "sf-judgment-db-"));
	tmpRoots.push(root);
	return root;
}

test("appendJudgment_writes_to_project_db", () => {
	const project = makeProject();

	appendJudgment(project, {
		unitId: "M001/S01/T01",
		decision: "Use DB",
		alternatives: ["JSONL"],
		reasoning: "queryable state",
		confidence: "high",
	});

	const entries = readJudgmentLog(project, "M001");
	assert.equal(entries.length, 1);
	assert.equal(entries[0].decision, "Use DB");
	assert.deepEqual(entries[0].alternatives, ["JSONL"]);
});

test("appendJudgment_when_switching_projects_uses_current_project_db", () => {
	const first = makeProject();
	const second = makeProject();

	appendJudgment(first, {
		unitId: "M001/S01/T01",
		decision: "first",
		confidence: "high",
	});
	appendJudgment(second, {
		unitId: "M001/S01/T01",
		decision: "second",
		confidence: "high",
	});

	closeDatabase();
	openDatabase(join(first, ".sf", "sf.db"));
	assert.deepEqual(
		getJudgmentsForUnit("M001").map((entry) => entry.decision),
		["first"],
	);
	closeDatabase();
	openDatabase(join(second, ".sf", "sf.db"));
	assert.deepEqual(
		getJudgmentsForUnit("M001").map((entry) => entry.decision),
		["second"],
	);
});
