import { execFileSync } from "node:child_process";
import { GIT_NO_PROMPT_ENV } from "./git-constants.js";

const PROTECTED_SNAPSHOT_DELETE_PATHS = [
	":(glob)src/resources/extensions/**/*.d.ts",
];

/**
 * List protected source files that are currently deleted.
 *
 * Purpose: keep automated stale-work snapshots from committing suspicious loss
 * of hand-written extension declaration files.
 *
 * Consumer: pre-dispatch and doctor git stale-change snapshot checks.
 */
export function listProtectedSnapshotDeletions(basePath, opts = {}) {
	const args = ["diff", "--name-only", "--diff-filter=D"];
	if (opts.cached === true) args.push("--cached");
	args.push("--", ...PROTECTED_SNAPSHOT_DELETE_PATHS);
	try {
		const out = execFileSync("git", args, {
			cwd: basePath,
			stdio: ["ignore", "pipe", "pipe"],
			encoding: "utf-8",
			env: GIT_NO_PROMPT_ENV,
		}).trim();
		return out ? out.split("\n").filter(Boolean) : [];
	} catch {
		return [];
	}
}

/**
 * Format a blocking diagnostic for protected snapshot deletions.
 *
 * Purpose: explain why SF refused an automated snapshot and name the files that
 * need an explicit human or task-level decision.
 *
 * Consumer: pre-dispatch and doctor git stale-change snapshot checks.
 */
export function formatProtectedSnapshotDeletionMessage(paths) {
	const shown = paths.slice(0, 8);
	const suffix =
		paths.length > shown.length
			? `, and ${paths.length - shown.length} more`
			: "";
	return `Protected declaration deletions detected; refusing automated snapshot: ${shown.join(", ")}${suffix}`;
}
