/**
 * auto/auto-post-unit-staging.js — Post-unit staging checks for doc-sync drift.
 *
 * Purpose: after code-mutating units, check whether ARCHITECTURE.md (and future
 * CONVENTIONS.md/STACK.md) are out of sync with the actual codebase. Advisory
 * — never blocks dispatch.
 *
 * Consumer: auto-post-unit.js postUnitPostVerification.
 */
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { debugLog } from "../debug-logger.js";
import { formatDocSyncProposal, getDocSyncProposal } from "../doc-sync.js";
import { getErrorMessage } from "../error-utils.js";
import { runGit } from "../git-service.js";

/** Unit types that mutate code — doc-sync only runs after these. */
const CODE_MUTATING_UNITS = new Set(["execute-task", "complete-slice"]);

/**
 * Run the doc-sync drift check after a code-mutating unit.
 *
 * @param {string} basePath - Project base path
 * @param {string} unitType - Type of the completed unit
 * @param {{ ui: { notify: (msg: string, level: string) => void } }} ctx - UI context
 */
export async function runDocSyncStagingCheck(basePath, unitType, ctx) {
	if (!CODE_MUTATING_UNITS.has(unitType)) {
		return;
	}

	try {
		const diffResult = runGit(basePath, [
			"diff",
			"--name-only",
			"HEAD~1",
			"HEAD",
		]);
		const changedFiles = diffResult?.stdout
			? diffResult.stdout.trim().split("\n").filter(Boolean)
			: [];
		if (changedFiles.length === 0) {
			return;
		}

		const proposals = getDocSyncProposal(
			changedFiles,
			{
				readFile: (p) => {
					try {
						return readFileSync(join(basePath, p), "utf-8");
					} catch {
						return null;
					}
				},
			},
			{
				glob: (_pat) => {
					try {
						const out = runGit(basePath, ["ls-files"]);
						return out?.stdout
							? out.stdout.trim().split("\n").filter(Boolean)
							: [];
					} catch {
						return [];
					}
				},
			},
		);

		if (proposals) {
			const msg = formatDocSyncProposal(proposals);
			if (msg) {
				ctx.ui.notify(msg, "info");
				debugLog("postUnit", {
					phase: "doc-sync",
					driftCount: proposals.reduce((n, p) => n + p.drift.length, 0),
				});
			}
		}
	} catch (e) {
		debugLog("postUnit", {
			phase: "doc-sync",
			error: getErrorMessage(e),
		});
	}
}
