#!/usr/bin/env node
import {
  safeLog
} from "./chunk-CYDXIW4L.js";
import "./chunk-UP2VWCW5.js";

// src/dashboard.ts
import { createServer } from "net";
import { spawn } from "child_process";
import { existsSync } from "fs";
import { join, resolve } from "path";
import { fileURLToPath } from "url";
var __dirname = fileURLToPath(new URL(".", import.meta.url));
var REPO_ROOT = resolve(__dirname, "..", "..", "..");
var MCP_WS_PORT = 6767;
var MCP_HTTP_PORT = 6768;
var FALLBACK_WS_PORT = 9092;
var FALLBACK_HTTP_PORT = 9093;
var DASHBOARD_PORT = 3200;
function isPortInUse(port) {
  return new Promise((resolve2) => {
    const server = createServer();
    server.once("error", () => resolve2(true));
    server.once("listening", () => {
      server.close();
      resolve2(false);
    });
    server.listen(port, "127.0.0.1");
  });
}
async function main() {
  const children = [];
  const cleanup = () => {
    safeLog.error("\n[RuntimeScope] Shutting down...");
    for (const child of children) {
      try {
        child.kill("SIGTERM");
      } catch {
      }
    }
    process.exit(0);
  };
  process.on("SIGINT", cleanup);
  process.on("SIGTERM", cleanup);
  const mcpRunning = await isPortInUse(MCP_HTTP_PORT);
  let collectorHttpPort;
  let collectorWsPort;
  let collectorProcess = null;
  if (mcpRunning) {
    try {
      const res = await fetch(`http://127.0.0.1:${MCP_HTTP_PORT}/api/health`);
      const data = await res.json();
      if (data.status === "ok") {
        safeLog.error(`[RuntimeScope] MCP server detected on :${MCP_HTTP_PORT}`);
        collectorHttpPort = MCP_HTTP_PORT;
        collectorWsPort = MCP_WS_PORT;
      } else {
        throw new Error("Not RuntimeScope");
      }
    } catch {
      safeLog.error(`[RuntimeScope] Port ${MCP_HTTP_PORT} in use (not RuntimeScope) \u2014 using fallback ports`);
      collectorHttpPort = FALLBACK_HTTP_PORT;
      collectorWsPort = FALLBACK_WS_PORT;
    }
  } else {
    collectorHttpPort = MCP_HTTP_PORT;
    collectorWsPort = MCP_WS_PORT;
  }
  const needsCollector = collectorHttpPort !== MCP_HTTP_PORT || !mcpRunning;
  if (needsCollector) {
    const standalonePath = join(__dirname, "standalone.js");
    if (!existsSync(standalonePath)) {
      safeLog.error("[RuntimeScope] Error: standalone.js not found. Run `npm run build -w packages/collector` first.");
      process.exit(1);
    }
    safeLog.error(`[RuntimeScope] Starting collector on ws://:${collectorWsPort} + http://:${collectorHttpPort}...`);
    collectorProcess = spawn("node", [standalonePath], {
      env: {
        ...process.env,
        RUNTIMESCOPE_PORT: String(collectorWsPort),
        RUNTIMESCOPE_HTTP_PORT: String(collectorHttpPort)
      },
      stdio: ["ignore", "ignore", "inherit"]
    });
    children.push(collectorProcess);
    for (let i = 0; i < 20; i++) {
      await new Promise((r) => setTimeout(r, 250));
      try {
        const res = await fetch(`http://127.0.0.1:${collectorHttpPort}/api/health`);
        if (res.ok) break;
      } catch {
      }
    }
  }
  try {
    const res = await fetch(`http://127.0.0.1:${collectorHttpPort}/api/health`);
    const data = await res.json();
    safeLog.error(`[RuntimeScope] Collector ready (${data.sessions ?? 0} sessions)`);
  } catch {
    safeLog.error(`[RuntimeScope] Warning: Could not reach collector on :${collectorHttpPort}`);
  }
  const dashboardDir = join(REPO_ROOT, "packages", "dashboard");
  if (!existsSync(dashboardDir)) {
    safeLog.error(`[RuntimeScope] Dashboard not found at ${dashboardDir}`);
    process.exit(1);
  }
  const dashboardInUse = await isPortInUse(DASHBOARD_PORT);
  if (dashboardInUse) {
    safeLog.error(`[RuntimeScope] Dashboard already running on http://localhost:${DASHBOARD_PORT}`);
    safeLog.error(`[RuntimeScope] Open http://localhost:${DASHBOARD_PORT} in your browser`);
    if (!needsCollector) process.exit(0);
    return;
  }
  safeLog.error(`[RuntimeScope] Starting dashboard on http://localhost:${DASHBOARD_PORT}...`);
  const vite = spawn("npx", ["vite", "--port", String(DASHBOARD_PORT)], {
    cwd: dashboardDir,
    env: {
      ...process.env,
      VITE_API_TARGET: `http://127.0.0.1:${collectorHttpPort}`
    },
    stdio: ["ignore", "pipe", "inherit"]
  });
  children.push(vite);
  vite.stdout?.on("data", (data) => {
    const line = data.toString();
    if (line.includes("Local:") || line.includes("ready")) {
    }
  });
  await new Promise((r) => setTimeout(r, 3e3));
  safeLog.error("");
  safeLog.error("  \u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557");
  safeLog.error("  \u2551          RuntimeScope Dashboard              \u2551");
  safeLog.error("  \u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");
  safeLog.error(`  \u2551  Dashboard:  http://localhost:${DASHBOARD_PORT}            \u2551`);
  safeLog.error(`  \u2551  Collector:  ws://127.0.0.1:${collectorWsPort}             \u2551`);
  safeLog.error(`  \u2551  HTTP API:   http://127.0.0.1:${collectorHttpPort}           \u2551`);
  safeLog.error(`  \u2551  Source:     ${mcpRunning && collectorHttpPort === MCP_HTTP_PORT ? "MCP Server (Claude Code)" : "Standalone Collector  "}  \u2551`);
  safeLog.error("  \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D");
  safeLog.error("");
  safeLog.error("  Press Ctrl+C to stop.");
  safeLog.error("");
  await new Promise(() => {
  });
}
main().catch((err) => {
  safeLog.error("[RuntimeScope] Fatal:", err);
  process.exit(1);
});
//# sourceMappingURL=dashboard.js.map