"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var dashboard_exports = {};
__export(dashboard_exports, {
  register: () => register
});
module.exports = __toCommonJS(dashboard_exports);
var path = __toESM(require("path"));
var fs = __toESM(require("fs"));
var http = __toESM(require("http"));
var import_ui = require("../ui");
var import_config = require("../../config");
function readJson(file) {
  try {
    return JSON.parse(fs.readFileSync(file, "utf8"));
  } catch {
    return null;
  }
}
function isAlive(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}
function killState(stateFile, pid, label_, portLabel) {
  let killed = false;
  if (isAlive(pid)) {
    try {
      process.kill(pid, "SIGTERM");
      killed = true;
    } catch {
    }
  }
  try {
    fs.unlinkSync(stateFile);
  } catch {
  }
  if (killed) {
    console.log(`  ${import_ui.green}\u2713${import_ui.reset} ${(0, import_ui.label)("Stopped")} ${label_}  ${import_ui.dim}(pid ${pid}, port ${portLabel})${import_ui.reset}`);
  } else {
    console.log(`  ${import_ui.dim}${label_} (pid ${pid}) was not running \u2014 state file cleaned up.${import_ui.reset}`);
  }
}
function qdrantDashboardReachable(port) {
  return new Promise((resolve) => {
    const req = http.get(`http://127.0.0.1:${port}/dashboard`, (res) => {
      resolve(res.statusCode !== 404);
      res.resume();
    });
    req.on("error", () => resolve(false));
    req.setTimeout(1e3, () => {
      req.destroy();
      resolve(false);
    });
  });
}
async function startTypesense(target) {
  const kirographDir = path.join(target, ".kirograph");
  const stateFile = path.join(kirographDir, "typesense-server.json");
  const saved = readJson(stateFile);
  if (saved && isAlive(saved.pid)) {
    console.log(`
  ${import_ui.green}\u2713${import_ui.reset} Typesense already running  ${import_ui.dim}(pid ${saved.pid}, port ${saved.apiPort})${import_ui.reset}`);
  } else {
    console.log();
    const { TypesenseIndex } = await Promise.resolve().then(() => require("../../vectors/typesense-index.js"));
    const index = new TypesenseIndex(kirographDir);
    await index.initialize();
    if (!index.isAvailable()) {
      console.log(`  Typesense failed to start.
`);
      return;
    }
    index.close();
  }
  const { openTypesenseDashboard } = await Promise.resolve().then(() => require("../installer/dashboard.js"));
  await openTypesenseDashboard(target);
  console.log(`  ${import_ui.dim}Press Ctrl+C to close the dashboard (Typesense keeps running \u2014 use ${import_ui.reset}kg dashboard stop${import_ui.dim} to shut it down).${import_ui.reset}
`);
  process.on("SIGINT", () => process.exit(0));
}
async function startQdrant(target) {
  const kirographDir = path.join(target, ".kirograph");
  const stateFile = path.join(kirographDir, "qdrant-server.json");
  const { ensureQdrantUI, openQdrantDashboard } = await Promise.resolve().then(() => require("../installer/qdrant-dashboard.js"));
  const uiReady = await ensureQdrantUI(target);
  if (!uiReady) {
    console.log(`  Could not download Qdrant Web UI.
`);
    return;
  }
  const saved = readJson(stateFile);
  if (saved && isAlive(saved.pid)) {
    const hasDashboard = await qdrantDashboardReachable(saved.port);
    if (hasDashboard) {
      console.log(`
  ${import_ui.green}\u2713${import_ui.reset} Qdrant already running with dashboard  ${import_ui.dim}(pid ${saved.pid}, port ${saved.port})${import_ui.reset}`);
      await openQdrantDashboard(target);
      console.log(`  ${import_ui.dim}Qdrant keeps running in the background \u2014 use ${import_ui.reset}kg dashboard stop${import_ui.dim} to shut it down.${import_ui.reset}
`);
      return;
    }
    try {
      process.kill(saved.pid, "SIGTERM");
    } catch {
    }
    await new Promise((r) => setTimeout(r, 400));
    try {
      fs.unlinkSync(stateFile);
    } catch {
    }
  }
  console.log();
  const { QdrantIndex } = await Promise.resolve().then(() => require("../../vectors/qdrant-index.js"));
  const index = new QdrantIndex(kirographDir);
  await index.initialize();
  if (!index.isAvailable()) {
    console.log(`  Qdrant failed to start.
`);
    return;
  }
  index.close();
  await openQdrantDashboard(target);
  console.log(`  ${import_ui.dim}Qdrant keeps running in the background \u2014 use ${import_ui.reset}kg dashboard stop${import_ui.dim} to shut it down.${import_ui.reset}
`);
}
function stopTypesense(target) {
  const stateFile = path.join(target, ".kirograph", "typesense-server.json");
  const saved = readJson(stateFile);
  if (!saved) {
    console.log(`  ${import_ui.dim}No running Typesense server found.${import_ui.reset}`);
    return;
  }
  killState(stateFile, saved.pid, "Typesense server", String(saved.apiPort));
}
function stopQdrant(target) {
  const stateFile = path.join(target, ".kirograph", "qdrant-server.json");
  const saved = readJson(stateFile);
  if (!saved) {
    console.log(`  ${import_ui.dim}No running Qdrant server found.${import_ui.reset}`);
    return;
  }
  killState(stateFile, saved.pid, "Qdrant server", String(saved.port));
}
function register(program) {
  const cmd = program.command("dashboard [projectPath]").description("Manage the engine dashboard (qdrant, typesense)");
  cmd.command("start [projectPath]").description("Start the engine server (if not running) and open its dashboard").action(async (projectPath) => {
    const target = path.resolve(projectPath ?? process.cwd());
    const config = await (0, import_config.loadConfig)(target);
    const engine = config.semanticEngine;
    if (engine === "typesense") return startTypesense(target);
    if (engine === "qdrant") return startQdrant(target);
    console.log(`
  ${import_ui.dim}Dashboard not available for engine "${engine}". Use qdrant or typesense.${import_ui.reset}
`);
  });
  cmd.command("stop [projectPath]").description("Stop the running engine server").action(async (projectPath) => {
    const target = path.resolve(projectPath ?? process.cwd());
    const config = await (0, import_config.loadConfig)(target);
    const engine = config.semanticEngine;
    console.log();
    if (engine === "typesense") {
      stopTypesense(target);
      console.log();
      return;
    }
    if (engine === "qdrant") {
      stopQdrant(target);
      console.log();
      return;
    }
    console.log(`  ${import_ui.dim}No dashboard engine active (current engine: "${engine}").${import_ui.reset}
`);
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  register
});
//# sourceMappingURL=dashboard.js.map
