const { app, BrowserWindow, ipcMain } = require("electron");
const path = require("path");
const fs = require("fs");
const readline = require("readline");

// Parse CLI args: --agent-id, --api-url, --environment, --function-id, --headless, --output-path
function parseArgs() {
  const args = {};
  const argv = process.argv.slice(2);
  for (let i = 0; i < argv.length; i++) {
    if (argv[i] === "--agent-id" && argv[i + 1]) args.agentId = argv[++i];
    else if (argv[i] === "--api-url" && argv[i + 1]) args.apiUrl = argv[++i];
    else if (argv[i] === "--environment" && argv[i + 1]) args.env = argv[++i];
    else if (argv[i] === "--function-id" && argv[i + 1])
      args.functionId = argv[++i];
    else if (argv[i] === "--headless") args.headless = true;
    else if (argv[i] === "--output-path" && argv[i + 1])
      args.outputPath = argv[++i];
    else if (argv[i] === "--script-path" && argv[i + 1])
      args.scriptPath = argv[++i];
  }
  return args;
}

app.name = "voicerun-debugger";

app.whenReady().then(() => {
  const args = parseArgs();

  const win = new BrowserWindow({
    width: 1400,
    height: 900,
    show: !args.headless,
    backgroundColor: "#0f172a",
    webPreferences: {
      webSecurity: false,
      preload: path.join(__dirname, "preload.js"),
    },
  });

  // Build query string from args
  const params = new URLSearchParams();
  if (args.agentId) params.set("agentId", args.agentId);
  if (args.env) params.set("env", args.env);
  if (args.apiUrl) params.set("apiUrl", args.apiUrl);
  if (args.functionId) params.set("functionId", args.functionId);
  if (args.headless) params.set("headless", "true");
  params.set("autoConnect", "true");

  // Handle save-and-quit IPC from renderer (headless mode)
  ipcMain.on("save-and-quit", (_event, jsonString) => {
    if (args.outputPath) {
      fs.writeFileSync(args.outputPath, jsonString, "utf-8");
    }
    app.quit();
  });

  // Relay events from renderer to stdout as JSONL (headless mode)
  ipcMain.on("headless-event", (_event, jsonString) => {
    process.stdout.write(jsonString + "\n");
  });

  // Read stdin line-by-line and forward to renderer as text input (headless mode)
  if (args.headless) {
    const rl = readline.createInterface({ input: process.stdin });
    rl.on("line", (line) => {
      win.webContents.send("stdin-text", line);
    });
    rl.on("close", () => {
      // stdin closed — let the session finish naturally
    });
  }

  // Send script messages to renderer once loaded
  if (args.scriptPath) {
    win.webContents.on("did-finish-load", () => {
      try {
        const scriptData = JSON.parse(
          fs.readFileSync(args.scriptPath, "utf-8")
        );
        win.webContents.send("script-load", scriptData);
      } catch (err) {
        console.error("Failed to load script file:", err.message);
      }
    });
  }

  const indexPath = path.join(__dirname, "index.html");
  const query = params.toString();
  win.loadFile(indexPath, { search: query });
});

app.on("window-all-closed", () => {
  app.quit();
});
