/**
 * SF Inspect — SQLite DB diagnostics.
 *
 * Contains: InspectData type, formatInspectOutput, handleInspect
 */
import { ensureDbOpen } from "./bootstrap/dynamic-tools.js";
import { getErrorMessage } from "./error-utils.js";
import { logWarning } from "./workflow-logger.js";
export function formatInspectOutput(data) {
	const lines = [];
	lines.push("=== SF Database Inspect ===");
	lines.push(`Schema version: ${data.schemaVersion ?? "unknown"}`);
	lines.push("");
	lines.push(`Decisions:    ${data.counts.decisions}`);
	lines.push(`Requirements: ${data.counts.requirements}`);
	lines.push(`Artifacts:    ${data.counts.artifacts}`);
	if (data.recentDecisions.length > 0) {
		lines.push("");
		lines.push("Recent decisions:");
		for (const d of data.recentDecisions) {
			lines.push(`  ${d.id}: ${d.decision} → ${d.choice}`);
		}
	}
	if (data.recentRequirements.length > 0) {
		lines.push("");
		lines.push("Recent requirements:");
		for (const r of data.recentRequirements) {
			lines.push(`  ${r.id} [${r.status}]: ${r.description}`);
		}
	}
	return lines.join("\n");
}
export async function handleInspect(ctx) {
	try {
		const { isDbAvailable, _getAdapter } = await import("./sf-db.js");
		if (!(await ensureDbOpen(process.cwd())) || !isDbAvailable()) {
			ctx.ui.notify(
				"No SF database available. Run /autonomous to create one.",
				"info",
			);
			return;
		}
		const adapter = _getAdapter();
		if (!adapter) {
			ctx.ui.notify(
				"No SF database available. Run /autonomous to create one.",
				"info",
			);
			return;
		}
		const versionRow = adapter
			.prepare("SELECT MAX(version) as v FROM schema_version")
			.get();
		const schemaVersion = versionRow ? versionRow["v"] : null;
		const dCount = adapter
			.prepare("SELECT count(*) as cnt FROM decisions")
			.get();
		const rCount = adapter
			.prepare("SELECT count(*) as cnt FROM requirements")
			.get();
		const aCount = adapter
			.prepare("SELECT count(*) as cnt FROM artifacts")
			.get();
		const recentDecisions = adapter
			.prepare(
				"SELECT id, decision, choice FROM decisions ORDER BY seq DESC LIMIT 5",
			)
			.all();
		const recentRequirements = adapter
			.prepare(
				"SELECT id, status, description FROM requirements ORDER BY id DESC LIMIT 5",
			)
			.all();
		const data = {
			schemaVersion,
			counts: {
				decisions: dCount?.["cnt"] ?? 0,
				requirements: rCount?.["cnt"] ?? 0,
				artifacts: aCount?.["cnt"] ?? 0,
			},
			recentDecisions,
			recentRequirements,
		};
		ctx.ui.notify(formatInspectOutput(data), "info");
	} catch (err) {
		logWarning("command", `/inspect failed: ${getErrorMessage(err)}`);
		ctx.ui.notify(
			"Failed to inspect SF database. Check stderr for details.",
			"error",
		);
	}
}
