#!/usr/bin/env node
"use strict";

const { execSync, spawn } = require("child_process");

function hasPython() {
  for (const cmd of ["python3", "python"]) {
    try {
      const v = execSync(`${cmd} --version`, { stdio: "pipe" }).toString().trim();
      if (v.startsWith("Python 3")) return cmd;
    } catch {}
  }
  return null;
}

function hasMyburnPip(py) {
  try {
    execSync(`${py} -m myburn --version`, { stdio: "pipe" });
    return true;
  } catch {
    return false;
  }
}

function main() {
  const py = hasPython();
  if (!py) {
    console.error("Error: Python 3.9+ is required but not found.");
    console.error("Install Python: https://www.python.org/downloads/");
    process.exit(1);
  }

  if (!hasMyburnPip(py)) {
    console.log("Installing myburn via pip...");
    try {
      execSync(`${py} -m pip install myburn`, { stdio: "inherit" });
    } catch {
      console.error("Failed to install myburn. Try: pip install myburn");
      process.exit(1);
    }
  }

  const args = process.argv.slice(2);
  const child = spawn(py, ["-m", "myburn", ...args], { stdio: "inherit" });
  child.on("exit", (code) => process.exit(code || 0));
}

main();
