/**
 * context7-retrieval-evidence.test.mjs — Context7 provenance coverage.
 *
 * Purpose: prove external documentation lookups write DB evidence with backend,
 * scope, freshness, and result metadata before agents trust indexed docs.
 */
import assert from "node:assert/strict";
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, test } from "vitest";
import registerContext7Extension from "../../context7/index.js";
import { closeDatabase, getRetrievalEvidence, openDatabase } from "../sf-db.js";

const tmpRoots = [];
const originalCwd = process.cwd();
const originalFetch = globalThis.fetch;

afterEach(() => {
	process.chdir(originalCwd);
	closeDatabase();
	globalThis.fetch = originalFetch;
	for (const root of tmpRoots.splice(0)) {
		rmSync(root, { recursive: true, force: true });
	}
});

function makeProject() {
	const root = mkdtempSync(join(tmpdir(), "sf-context7-evidence-"));
	tmpRoots.push(root);
	mkdirSync(join(root, ".sf"), { recursive: true });
	return root;
}

function captureContext7Tools() {
	const tools = new Map();
	registerContext7Extension({
		on() {},
		registerTool(definition) {
			tools.set(definition.name, definition);
		},
	});
	return tools;
}

test("resolve_library_when_successful_records_retrieval_evidence", async () => {
	const project = makeProject();
	process.chdir(project);
	assert.equal(openDatabase(join(project, ".sf", "sf.db")), true);
	globalThis.fetch = async (url) => {
		assert.match(String(url), /\/libs\/search/);
		return {
			ok: true,
			json: async () => ({
				results: [
					{
						id: "/websites/example_docs",
						title: "Example Docs",
						trustScore: 9,
						benchmarkScore: 87.5,
					},
				],
			}),
		};
	};

	const tools = captureContext7Tools();
	const result = await tools.get("resolve_library").execute("call-1", {
		libraryName: "example-docs-evidence",
		query: "routing",
	});

	assert.equal(result.details.resultCount, 1);
	const rows = getRetrievalEvidence(5);
	assert.equal(rows.length, 1);
	assert.equal(rows[0].backend, "context7");
	assert.equal(rows[0].sourceKind, "docs");
	assert.equal(rows[0].strategy, "library-search");
	assert.equal(rows[0].scope, "example-docs-evidence");
	assert.equal(rows[0].freshness, "external-index");
	assert.equal(rows[0].status, "ok");
	assert.equal(rows[0].hitCount, 1);
	assert.deepEqual(rows[0].result.libraries, [
		{
			id: "/websites/example_docs",
			title: "Example Docs",
			trustScore: 9,
			benchmarkScore: 87.5,
		},
	]);
});

test("get_library_docs_when_successful_records_retrieval_evidence", async () => {
	const project = makeProject();
	process.chdir(project);
	assert.equal(openDatabase(join(project, ".sf", "sf.db")), true);
	globalThis.fetch = async (url) => {
		assert.match(String(url), /\/context/);
		return {
			ok: true,
			text: async () => "Example docs about routing.",
		};
	};

	const tools = captureContext7Tools();
	const result = await tools.get("get_library_docs").execute("call-1", {
		libraryId: "/websites/example_docs",
		query: "routing",
		tokens: 500,
	});

	assert.equal(result.details.charCount, "Example docs about routing.".length);
	const rows = getRetrievalEvidence(5);
	assert.equal(rows.length, 1);
	assert.equal(rows[0].backend, "context7");
	assert.equal(rows[0].sourceKind, "docs");
	assert.equal(rows[0].strategy, "docs-fetch");
	assert.equal(rows[0].scope, "/websites/example_docs");
	assert.equal(rows[0].freshness, "external-index");
	assert.equal(rows[0].status, "ok");
	assert.equal(rows[0].hitCount, 1);
	assert.equal(rows[0].result.tokens, 500);
	assert.equal(rows[0].result.charCount, "Example docs about routing.".length);
});
