import { spawn } from "node:child_process";

const debugEnvironment = { ...process.env };
const clearedVariables = [];
const blockedProxy = /^https?:\/\/127\.0\.0\.1:9\/?$/i;
const proxyVariables = new Set([
  "all_proxy",
  "http_proxy",
  "https_proxy",
  "git_http_proxy",
  "git_https_proxy",
]);

for (const [name, value] of Object.entries(debugEnvironment)) {
  if (proxyVariables.has(name.toLowerCase()) && blockedProxy.test(value ?? "")) {
    delete debugEnvironment[name];
    clearedVariables.push(name);
  }
}

for (const [name, value] of Object.entries(debugEnvironment)) {
  if (
    name.toLowerCase() === "git_ssh_command"
    && /^cmd(?:\.exe)?\s+\/c\s+exit\s+1$/i.test((value ?? "").trim())
  ) {
    delete debugEnvironment[name];
    clearedVariables.push(name);
  }
}

if (process.argv.includes("--check-environment")) {
  process.stdout.write(
    clearedVariables.length > 0
      ? `Debug environment ready; cleared: ${clearedVariables.sort().join(", ")}\n`
      : "Debug environment ready; no blocked proxy variables found.\n",
  );
  process.exit(0);
}

if (clearedVariables.length > 0) {
  process.stdout.write(
    `Starting Gitty without the blocked debug proxy (${clearedVariables.sort().join(", ")}).\n`,
  );
}

const isWindows = process.platform === "win32";
const child = spawn(isWindows ? "tauri.cmd" : "tauri", ["dev"], {
  cwd: process.cwd(),
  env: debugEnvironment,
  stdio: "inherit",
  shell: isWindows,
});

child.on("error", (error) => {
  process.stderr.write(`Could not start Tauri development mode: ${error.message}\n`);
  process.exitCode = 1;
});

child.on("exit", (code) => {
  process.exitCode = code ?? 1;
});
