#!/usr/bin/env node

// src/cli.ts
import { spawn, execSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
var __filename = fileURLToPath(import.meta.url);
var __dirname = dirname(__filename);
var DEFAULT_PORT = 25947;
var envPort = process.env["PORT"];
var portDefault = envPort !== void 0 ? Number(envPort) : DEFAULT_PORT;
var args = process.argv.slice(2);
var port = portDefault;
var open = true;
var configDir;
var providersJson;
for (let i = 0; i < args.length; i++) {
  const arg = args[i] ?? "";
  switch (arg) {
    case "--port":
    case "-p":
      port = Number(args[i + 1]);
      i++;
      break;
    case "--no-open":
      open = false;
      break;
    case "--open":
      open = true;
      break;
    case "--config-dir":
      configDir = args[i + 1];
      i++;
      break;
    case "--providers":
      providersJson = args[i + 1];
      i++;
      break;
    default:
      break;
  }
}
function killProcessOnPort(targetPort) {
  const platform = process.platform;
  try {
    let pids = [];
    if (platform === "win32") {
      const output = execSync(`netstat -ano | findstr :${targetPort}`, {
        encoding: "utf8",
        timeout: 5e3
      });
      const lines = output.trim().split("\n");
      for (const line of lines) {
        const parts = line.trim().split(/\s+/);
        if (parts.length >= 5) {
          const localAddress = parts[1] ?? "";
          const pidStr = parts[4] ?? "";
          if (localAddress !== "" && pidStr !== "" && localAddress.includes(`:${targetPort}`)) {
            const pid = parseInt(pidStr, 10);
            if (!isNaN(pid) && pid > 0) {
              pids.push(pid);
            }
          }
        }
      }
      pids = [...new Set(pids)];
      for (const pid of pids) {
        try {
          console.log(`Killing process ${pid} on port ${port}...`);
          execSync(`taskkill /PID ${pid} /F`, { encoding: "utf8", timeout: 5e3 });
        } catch {
        }
      }
    } else {
      const output = execSync(`lsof -ti:${targetPort}`, { encoding: "utf8", timeout: 5e3 });
      const lines = output.trim().split("\n");
      for (const line of lines) {
        const pid = parseInt(line.trim(), 10);
        if (!isNaN(pid) && pid > 0) {
          pids.push(pid);
        }
      }
      pids = [...new Set(pids)];
      for (const pid of pids) {
        try {
          console.log(`Killing process ${pid} on port ${targetPort}...`);
          execSync(`kill -9 ${pid}`, { encoding: "utf8", timeout: 5e3 });
        } catch {
        }
      }
    }
  } catch {
  }
}
process.env["PORT"] = String(port);
killProcessOnPort(port);
var url = `http://localhost:${port}`;
console.log(`Server running at ${url}`);
console.log(`   Proxy: ${url}/proxy`);
console.log(``);
console.log(`Route AI coding tools through the proxy:`);
console.log(`   Claude Code:  ANTHROPIC_BASE_URL=${url}/proxy claude`);
console.log(`   OpenCode:     LLM_BASE_URL=${url}/proxy opencode`);
console.log(`   MiMo Code:    OPENAI_BASE_URL=${url}/proxy mimo`);
console.log(`   Direct HTTP:  curl ${url}/proxy/v1/messages -d '{"model":"...","messages":[...]}'`);
console.log(``);
console.log(`Routing environment variables:`);
console.log(`   ROUTES            JSON map of model prefix -> upstream URL`);
console.log(`   DEFAULT_UPSTREAM  Fallback upstream for unmatched models`);
console.log(
  `   Example: ROUTES='{"claude-":"https://api.anthropic.com","MiniMax":"https://api.minimaxi.com/anthropic"}'`
);
var openBrowser = (targetUrl) => {
  let command;
  switch (process.platform) {
    case "darwin":
      command = ["open", targetUrl];
      break;
    case "linux":
      command = ["xdg-open", targetUrl];
      break;
    case "win32":
      command = ["cmd", "/c", "start", targetUrl];
      break;
    default:
      break;
  }
  if (command === void 0) return;
  const [bin, ...cmdArgs] = command;
  if (bin === void 0) return;
  spawn(bin, cmdArgs, { stdio: "ignore", detached: true });
};
if (open) {
  openBrowser(url);
}
var outputDir = __dirname;
var serverPath = join(outputDir, "../.output/server/index.mjs");
var serverEnv = { ...process.env };
if (configDir !== void 0) {
  let resolvedPath = join(configDir, "config.json");
  if (resolvedPath.startsWith("\\c\\")) {
    resolvedPath = "C:" + resolvedPath;
  }
  serverEnv["LLM_INSPECTOR_CONFIG_PATH"] = resolvedPath;
}
if (providersJson !== void 0) {
  serverEnv["LLM_INSPECTOR_PROVIDERS_JSON"] = providersJson;
}
var serverProcess = spawn(process.execPath, [serverPath], {
  stdio: ["ignore", "inherit", "inherit"],
  detached: true,
  env: serverEnv
});
serverProcess.unref();
