import console from "node:console";
import { execFileSync } from "node:child_process";
import process from "node:process";
import {
  cpSync,
  existsSync,
  mkdtempSync,
  mkdirSync,
  readFileSync,
  rmSync,
  writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";

const frameworkRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const root = mkdtempSync(join(tmpdir(), "wrnexus-workspace-repair-"));

function git(args) {
  return execFileSync("git", args, {
    cwd: root,
    encoding: "utf8",
    stdio: ["ignore", "pipe", "pipe"],
  });
}

try {
  mkdirSync(join(root, "scripts"), { recursive: true });
  mkdirSync(join(root, "examples", "basic-app"), { recursive: true });
  cpSync(
    join(frameworkRoot, "scripts", "repair-workspace.mjs"),
    join(root, "scripts", "repair-workspace.mjs"),
  );
  writeFileSync(
    join(root, ".gitignore"),
    [".env", ".env.*", "!.env.example", "!.env.*.example", ""].join("\n"),
  );
  writeFileSync(join(root, "examples", "basic-app", ".env.example"), "TOKEN=replace-me\n");
  writeFileSync(join(root, "examples", "basic-app", ".env.uat.example"), "TOKEN=replace-me\n");

  git(["init", "-q"]);
  git(["config", "user.email", "test@wrnexus.invalid"]);
  git(["config", "user.name", "WRNexus Test"]);
  git(["add", "-A"]);
  git(["commit", "-qm", "baseline"]);

  writeFileSync(join(root, "examples", "basic-app", ".env"), "TOKEN=keep-local\n");
  writeFileSync(join(root, "examples", "basic-app", ".env.uat"), "TOKEN=keep-local-uat\n");
  writeFileSync(join(root, "focus-shims.d.ts"), "declare const Bun: any;\n");
  writeFileSync(join(root, "tsconfig.focus.json"), "{}\n");
  git([
    "add",
    "-f",
    "examples/basic-app/.env",
    "examples/basic-app/.env.uat",
    "focus-shims.d.ts",
    "tsconfig.focus.json",
  ]);
  git(["commit", "-qm", "unsafe local state"]);

  execFileSync(process.execPath, [join(root, "scripts", "repair-workspace.mjs")], {
    cwd: root,
    stdio: "pipe",
  });

  if (readFileSync(join(root, "examples", "basic-app", ".env"), "utf8") !== "TOKEN=keep-local\n") {
    throw new Error("Local .env value was modified or removed.");
  }
  if (
    readFileSync(join(root, "examples", "basic-app", ".env.uat"), "utf8") !==
    "TOKEN=keep-local-uat\n"
  ) {
    throw new Error("Local .env.uat value was modified or removed.");
  }
  if (existsSync(join(root, "focus-shims.d.ts")) || existsSync(join(root, "tsconfig.focus.json"))) {
    throw new Error("Temporary typecheck files were not removed.");
  }

  const tracked = git(["ls-files", "-z"]).split("\0").filter(Boolean);
  const secretPattern = /(?:^|\/)(?:\.env(?:\..+)?|focus-shims\.d\.ts|tsconfig\.focus\.json)$/i;
  const safeTemplate = /(?:^|\/)\.env(?:\.[^/]+)*\.(?:example|sample|template)$/i;
  const forbidden = tracked.filter((path) => secretPattern.test(path) && !safeTemplate.test(path));
  if (forbidden.length > 0) {
    throw new Error(`Unsafe files remain tracked: ${forbidden.join(", ")}`);
  }

  console.log("Workspace repair regression test passed.");
} finally {
  rmSync(root, { recursive: true, force: true });
}
