const path = require("path");
const { spawn } = require("child_process");
const { createUiServer, pkgUiDir } = require("../lib/ui-server");

module.exports = async function ui(args, flags) {
  const rootDir = process.cwd();
  const port = Number(flags.port || 3721);
  const host = flags.host || "127.0.0.1";
  const uiDir = flags["ui-dir"] ? path.resolve(flags["ui-dir"]) : pkgUiDir();
  const fs = require("fs");

  if (!fs.existsSync(path.join(rootDir, "skill-routing-matrix.json"))) {
    console.error("Not a CapInt project — run capint init in this directory first.");
    process.exit(1);
  }
  if (!fs.existsSync(uiDir)) {
    console.error(`UI assets not found: ${uiDir}`);
    process.exit(1);
  }

  const app = createUiServer({ rootDir, uiDir, port, host });
  const info = await app.listen();

  if (flags.json) {
    console.log(JSON.stringify({ ...info, rootDir }, null, 2));
    if (!flags.open) return;
  } else {
    console.log("\n## CapInt UI\n");
    console.log(`Project: ${rootDir}`);
    console.log(`Open: ${info.url}`);
    console.log("Press Ctrl+C to stop.\n");
  }

  if (flags.open) {
    const url = info.url;
    if (process.platform === "win32") {
      spawn("cmd", ["/c", "start", "", url], { detached: true, stdio: "ignore" }).unref();
    } else if (process.platform === "darwin") {
      spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
    } else {
      spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
    }
  }

  await new Promise((resolve) => {
    process.on("SIGINT", () => {
      app.close().then(resolve);
    });
  });
};
