import { execSync } from "node:child_process";
import path from "node:path";

const DEFAULT_WSL_DISTRO = "Ubuntu-22.04";

function toWslPath(winPath: string): string {
  const normalized = path.resolve(winPath);
  const match = normalized.match(/^([a-zA-Z]):[\\/]+(.*)/);
  if (!match) {
    return normalized.replace(/\\/g, "/");
  }
  return `/mnt/${match[1].toLowerCase()}/${match[2].replace(/\\/g, "/")}`;
}

/** Windows + DEV_INFRA_MODE=native 时自动拉起 WSL mysql/redis */
export function ensureNativeInfraIfNeeded(): void {
  if (process.env.SKIP_NATIVE_INFRA_BOOTSTRAP === "true") {
    return;
  }
  if (process.platform !== "win32") {
    return;
  }
  const mode = process.env.DEV_INFRA_MODE?.trim().toLowerCase();
  if (mode !== "native") {
    return;
  }

  const scriptPath = path.join(
    process.cwd(),
    "scripts",
    "dev",
    "wsl-infra.sh",
  );
  const wslScript = toWslPath(scriptPath);
  const distro = process.env.WSL_DISTRO?.trim() || DEFAULT_WSL_DISTRO;
  const mysqlPort = process.env.MYSQL_HOST_PORT?.trim() || "3307";
  const mysqlPassword =
    process.env.MYSQL_ROOT_PASSWORD?.trim() || "changeme";

  console.log(`[infra] 确保 WSL 基础设施就绪 (distro=${distro})…`);
  execSync(
    `wsl -d ${distro} bash -c "export MYSQL_HOST_PORT=${mysqlPort} MYSQL_ROOT_PASSWORD=${mysqlPassword}; bash '${wslScript}' start"`,
    { stdio: "pipe", timeout: 90_000, windowsHide: true },
  );
}
