/**
 * sf-learning plugin entrypoint tests.
 *
 * Exercises init-time wiring against a real Node built-in SQLite database so
 * the plugin cannot regress to an undeclared external SQLite binding.
 */

import assert from "node:assert/strict";
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "vitest";
import { closeDatabase } from "../sf-db.js";
import { init } from "./index.mjs";

function createMockPi() {
	const handlers = [];
	return {
		handlers,
		on(event, handler) {
			if (event === "before_model_select") handlers.push(handler);
		},
		off(event, handler) {
			if (event !== "before_model_select") return;
			const index = handlers.indexOf(handler);
			if (index >= 0) handlers.splice(index, 1);
		},
	};
}

test("init_when_no_db_is_injected_uses_shared_sf_database", async () => {
	const tmp = mkdtempSync(join(tmpdir(), "sf-learning-"));
	const dbPath = join(tmp, ".sf", "sf.db");
	let plugin;

	try {
		plugin = await init(createMockPi(), {
			basePath: tmp,
			explorationEnabled: false,
		});

		assert.equal(existsSync(dbPath), true);
		assert.equal(
			plugin.recordOutcome({
				modelId: "test/model",
				provider: "test",
				unitType: "execute-task",
				unitId: "M001/S01/T01",
				succeeded: true,
			}),
			true,
		);

		const row = plugin.deps.db
			.prepare("SELECT COUNT(*) AS count FROM llm_task_outcomes")
			.get();
		assert.equal(row.count, 1);
	} finally {
		plugin?.unregister?.();
		closeDatabase();
		rmSync(tmp, { recursive: true, force: true });
	}
});
