/**
 * commands-harness.ts - repo-native harness evolution commands.
 *
 * Purpose: expose the read-only profiler so operators can seed harness
 * evolution state without changing prompts or claiming untracked files.
 */

import { join } from "node:path";
import type { ExtensionCommandContext } from "@singularity-forge/pi-coding-agent";
import { ensureDbOpen } from "./bootstrap/dynamic-tools.js";
import { projectRoot } from "./commands/context.js";
import { profileRepository } from "./repo-profiler.js";
import { recordRepoProfile } from "./sf-db.js";

/**
 * Format a repo profile summary for user notification.
 */
function formatProfileSummary(
	profile: ReturnType<typeof profileRepository>,
): string {
	const untracked = profile.git.changedFiles.filter(
		(file) => file.gitStatus === "untracked",
	).length;
	const modified = profile.git.changedFiles.filter(
		(file) => file.gitStatus === "modified",
	).length;
	const stacks =
		profile.stacks
			.map((stack) => stack.kind)
			.filter(Boolean)
			.join(", ") || "none detected";
	const risks =
		profile.riskHints
			.map((hint) => hint.family)
			.filter(Boolean)
			.join(", ") || "none detected";

	return [
		"Repo harness profile recorded",
		`Profile: ${profile.profileId}`,
		`State: ${join(profile.projectRoot, ".sf", "sf.db")}`,
		`Branch: ${profile.git.branch ?? "unknown"}`,
		`Changed files: ${profile.git.changedFiles.length} (${modified} modified, ${untracked} untracked)`,
		`Stacks: ${stacks}`,
		`Risk hints: ${risks}`,
		"",
		"Untracked files were recorded as observations only; SF did not stage or adopt them.",
	].join("\n");
}

/**
 * Run repo harness profiling and persist the resulting snapshot.
 *
 * Purpose: give users and future auto-flow slices an explicit entry point for
 * harness evolution's read-only observation phase.
 *
 * Consumer: `/sf harness profile` command.
 */
export async function handleHarness(
	args: string,
	ctx: ExtensionCommandContext,
): Promise<void> {
	const subcommand = args.trim() || "profile";
	if (!["profile", "snapshot", "status"].includes(subcommand)) {
		ctx.ui.notify(
			"Usage: /sf harness profile\nRecords a read-only repo profile for harness evolution.",
			"warning",
		);
		return;
	}

	const basePath = projectRoot();
	const opened = await ensureDbOpen(basePath);
	if (!opened) {
		ctx.ui.notify("No SF database available. Run /sf init first.", "warning");
		return;
	}

	const profile = profileRepository(basePath);
	recordRepoProfile(profile);
	ctx.ui.notify(formatProfileSummary(profile), "info");
}
