#!/usr/bin/env node
import { execFileSync } from "node:child_process";

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

function git(args) {
	return execFileSync("git", args, {
		stdio: ["ignore", "pipe", "pipe"],
		encoding: "utf-8",
	}).trim();
}

function listDeleted(cached) {
	const args = ["diff", "--name-only", "--diff-filter=D"];
	if (cached) args.push("--cached");
	args.push("--", ...PROTECTED_PATHS);
	const out = git(args);
	return out ? out.split("\n").filter(Boolean) : [];
}

const stagedOnly = process.argv.includes("--cached");
const deleted = stagedOnly
	? listDeleted(true)
	: [...new Set([...listDeleted(false), ...listDeleted(true)])];

if (deleted.length > 0) {
	const mode = stagedOnly ? "staged " : "";
	process.stderr.write(
		`check-protected-deletions: refusing ${mode}protected declaration deletions:\n`,
	);
	for (const path of deleted) {
		process.stderr.write(`  ${path}\n`);
	}
	process.stderr.write(
		"\nRestore these files or make an explicit reviewed deletion outside automation.\n",
	);
	process.exit(1);
}

process.stdout.write("check-protected-deletions: ok\n");
