/**
 * retrieval-evidence.js — DB-backed retrieval provenance helpers.
 *
 * Purpose: give local code, docs, and web retrieval tools one audit contract so
 * agents can distinguish live source evidence from stale or external context.
 *
 * Consumer: `sift_search`, `codebase_search`, and future Context7/web bridges.
 */
import { execFileSync } from "node:child_process";

function readGitValue(projectRoot, args) {
	try {
		return execFileSync("git", args, {
			cwd: projectRoot,
			encoding: "utf-8",
			stdio: ["ignore", "pipe", "ignore"],
			timeout: 2_000,
		}).trim();
	} catch {
		return "";
	}
}

/**
 * Build best-effort git provenance for a retrieval event.
 * Purpose: label whether a context hit came from clean HEAD, a dirty worktree,
 * or an unknown non-git directory before it is trusted for planning.
 * Consumer: retrieval evidence writers.
 */
export function buildRetrievalProvenance(projectRoot) {
	const gitHead = readGitValue(projectRoot, ["rev-parse", "HEAD"]) || null;
	const gitBranch =
		readGitValue(projectRoot, ["branch", "--show-current"]) ||
		readGitValue(projectRoot, ["rev-parse", "--abbrev-ref", "HEAD"]) ||
		null;
	const status = readGitValue(projectRoot, ["status", "--porcelain"]);
	return {
		gitHead,
		gitBranch,
		worktreeDirty: status.length > 0,
		freshness: gitHead
			? status.length > 0
				? "working-tree"
				: "git-head"
			: "unknown",
	};
}

/**
 * Record retrieval evidence without making retrieval depend on DB availability.
 * Purpose: preserve provenance when the SF DB is open while letting search tools
 * degrade normally in standalone or early-startup contexts.
 * Consumer: local retrieval tool implementations.
 */
export async function recordRetrievalEvidence(projectRoot, entry) {
	try {
		const { insertRetrievalEvidence } = await import("./sf-db.js");
		insertRetrievalEvidence({
			projectRoot,
			...buildRetrievalProvenance(projectRoot),
			...entry,
		});
	} catch {
		// Retrieval evidence is best-effort; search results must remain usable.
	}
}
