"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 installer_exports = {};
__export(installer_exports, {
  runInstaller: () => runInstaller
});
module.exports = __toCommonJS(installer_exports);
var readline = __toESM(require("readline"));
var fs = __toESM(require("fs"));
var path = __toESM(require("path"));
var import_child_process = require("child_process");
var import_config = require("../../config");
var import_banner = require("../banner");
var import_progress = require("../progress");
var import_ui = require("../ui");
var import_prompts = require("./prompts");
var import_config_prompt = require("./config-prompt");
var import_dashboard = require("./dashboard");
var import_qdrant_dashboard = require("./qdrant-dashboard");
var import_targets = require("./targets");
async function runInstaller(target = "kiro") {
  (0, import_banner.printBanner)();
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  try {
    const cwd = process.cwd();
    const installer = (0, import_targets.getTargetInstaller)(target);
    console.log(`  Workspace: ${cwd}
`);
    const proceed = await (0, import_prompts.askToggle)(rl, `Install KiroGraph for ${installer.label}?`, "Registers the MCP server and writes integration files for this workspace.");
    if (!proceed) {
      console.log("  Cancelled.");
      rl.close();
      return;
    }
    console.log();
    installer.installEarly(cwd);
    const alreadyInitialized = fs.existsSync(path.join(cwd, ".kirograph"));
    let cavemanMode = "off";
    let shellCompressionLevel = "normal";
    let enableMemory = false;
    let enableDocs = false;
    let shouldOfferIndex = false;
    let typesenseDashboard = false;
    let qdrantDashboard = false;
    try {
      if (alreadyInitialized) {
        const config = await (0, import_config.loadConfig)(cwd);
        cavemanMode = config.cavemanMode ?? "off";
        shellCompressionLevel = config.shellCompressionLevel ?? "normal";
        enableMemory = config.enableMemory ?? false;
        enableDocs = config.enableDocs ?? false;
        console.log(`  \u2713 Reusing existing KiroGraph data in ${cwd}/.kirograph/`);
        console.log(`  \u2022 semanticEngine: ${config.semanticEngine}`);
        console.log(`  \u2022 enableEmbeddings: ${config.enableEmbeddings}`);
        console.log(`  \u2022 enableArchitecture: ${config.enableArchitecture}`);
        console.log(`  \u2022 cavemanMode: ${cavemanMode}`);
        console.log(`  \u2022 shellCompressionLevel: ${shellCompressionLevel}`);
        console.log(`  \u2022 enableMemory: ${enableMemory}`);
        console.log(`  \u2022 enableDocs: ${enableDocs}`);
      } else {
        shouldOfferIndex = true;
        const patch = await (0, import_config_prompt.promptConfigOptions)(rl);
        await (0, import_config.updateConfig)(cwd, patch);
        cavemanMode = patch.cavemanMode ?? "off";
        shellCompressionLevel = patch.shellCompressionLevel ?? "normal";
        enableMemory = patch.enableMemory ?? false;
        enableDocs = patch.enableDocs ?? false;
        typesenseDashboard = patch.typesenseDashboard;
        qdrantDashboard = patch.qdrantDashboard;
        console.log(`
  Configuration saved to ${cwd}/.kirograph/config.json`);
        console.log(`  \u2022 enableEmbeddings: ${patch.enableEmbeddings}`);
        if ("embeddingModel" in patch) {
          console.log(`  \u2022 embeddingModel: ${patch.embeddingModel}  ${import_ui.dim}(${patch.embeddingDim}-dim)${import_ui.reset}`);
        }
        if (patch.enableEmbeddings) {
          console.log(`  \u2022 semanticEngine: ${patch.semanticEngine}`);
          if (patch.semanticEngine === "sqlite-vec") {
            console.log(`
  Installing sqlite-vec dependencies...`);
            const result = (0, import_child_process.spawnSync)("npm", ["install", "better-sqlite3", "sqlite-vec"], { stdio: "inherit", shell: true });
            if (result.status === 0) {
              console.log(`  \u2713 better-sqlite3 and sqlite-vec installed`);
            } else {
              console.warn(`  \u2717 npm install failed (exit ${result.status}). Run manually:`);
              console.warn(`    npm install better-sqlite3 sqlite-vec`);
            }
          } else if (patch.semanticEngine === "orama") {
            console.log(`
  Installing Orama dependencies...`);
            const result = (0, import_child_process.spawnSync)("npm", ["install", "@orama/orama", "@orama/plugin-data-persistence"], { stdio: "inherit", shell: true });
            if (result.status === 0) {
              console.log(`  \u2713 @orama/orama and @orama/plugin-data-persistence installed`);
            } else {
              console.warn(`  \u2717 npm install failed (exit ${result.status}). Run manually:`);
              console.warn(`    npm install @orama/orama @orama/plugin-data-persistence`);
            }
          } else if (patch.semanticEngine === "pglite") {
            console.log(`
  Installing PGlite dependencies...`);
            const result = (0, import_child_process.spawnSync)("npm", ["install", "@electric-sql/pglite"], { stdio: "inherit", shell: true });
            if (result.status === 0) {
              console.log(`  \u2713 @electric-sql/pglite installed`);
            } else {
              console.warn(`  \u2717 npm install failed (exit ${result.status}). Run manually:`);
              console.warn(`    npm install @electric-sql/pglite`);
            }
          } else if (patch.semanticEngine === "lancedb") {
            console.log(`
  Installing LanceDB dependencies...`);
            const result = (0, import_child_process.spawnSync)("npm", ["install", "@lancedb/lancedb"], { stdio: "inherit", shell: true });
            if (result.status === 0) {
              console.log(`  \u2713 @lancedb/lancedb installed`);
            } else {
              console.warn(`  \u2717 npm install failed (exit ${result.status}). Run manually:`);
              console.warn(`    npm install @lancedb/lancedb`);
            }
          } else if (patch.semanticEngine === "qdrant") {
            console.log(`
  Installing Qdrant dependencies...`);
            const result = (0, import_child_process.spawnSync)("npm", ["install", "qdrant-local"], { stdio: "inherit", shell: true });
            if (result.status === 0) {
              console.log(`  \u2713 qdrant-local installed`);
            } else {
              console.warn(`  \u2717 npm install failed (exit ${result.status}). Run manually:`);
              console.warn(`    npm install qdrant-local`);
            }
          } else if (patch.semanticEngine === "typesense") {
            console.log(`
  Installing Typesense dependencies...`);
            const result = (0, import_child_process.spawnSync)("npm", ["install", "typesense"], { stdio: "inherit", shell: true });
            if (result.status === 0) {
              console.log(`  \u2713 typesense installed`);
              console.log(`  \u2139  The Typesense binary (~37MB) will be auto-downloaded on first index run.`);
            } else {
              console.warn(`  \u2717 npm install failed (exit ${result.status}). Run manually:`);
              console.warn(`    npm install typesense`);
            }
          }
        }
        console.log(`  \u2022 extractDocstrings: ${patch.extractDocstrings}`);
        console.log(`  \u2022 trackCallSites: ${patch.trackCallSites}`);
        console.log(`  \u2022 enableArchitecture: ${patch.enableArchitecture}`);
        console.log(`  \u2022 cavemanMode: ${cavemanMode}`);
        console.log(`  \u2022 shellCompressionLevel: ${shellCompressionLevel}`);
        console.log(`  \u2022 enableMemory: ${enableMemory}`);
        console.log(`  \u2022 enableDocs: ${enableDocs}`);
      }
      installer.installLate(cwd, cavemanMode, shellCompressionLevel, enableMemory, enableDocs);
    } catch (err) {
      const reason = err instanceof Error ? err.message : String(err);
      console.error(`
  \u2717 Failed to write configuration: ${reason}`);
      process.exit(1);
    }
    if (qdrantDashboard) {
      await (0, import_qdrant_dashboard.ensureQdrantUI)(cwd);
    }
    if (shouldOfferIndex && await (0, import_prompts.askToggle)(rl, "Initialize and index this project now?", "Creates .kirograph/ and indexes all source files. Takes a few seconds for small projects, longer for large ones.")) {
      const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
      const fileBytes = /* @__PURE__ */ new Map();
      const modelProgress = (file, loaded, total, done) => {
        const entry = fileBytes.get(file) ?? { loaded: 0, total: 0 };
        if (total > 0) entry.total = total;
        entry.loaded = done ? entry.total : loaded;
        fileBytes.set(file, entry);
        const knownFiles = Array.from(fileBytes.values()).filter((f) => f.total > 0);
        const totalLoaded = knownFiles.reduce((s, f) => s + f.loaded, 0);
        const totalBytes = knownFiles.reduce((s, f) => s + f.total, 0);
        const pct = totalBytes > 0 ? Math.min(totalLoaded / totalBytes * 100, 100) : 0;
        const filled = Math.round(pct / 5);
        const bar = "\u2588".repeat(filled) + "\u2591".repeat(20 - filled);
        const mb = (totalLoaded / 1024 / 1024).toFixed(1);
        const totalMb = (totalBytes / 1024 / 1024).toFixed(1);
        process.stdout.write(`\r  [${bar}] ${pct.toFixed(0).padStart(3)}%  ${mb} / ${totalMb} MB   `);
      };
      const originalStderrWrite = process.stderr.write.bind(process.stderr);
      const stderrFilter = (chunk, ...args) => {
        const str = typeof chunk === "string" ? chunk : String(chunk);
        if (str.includes("content-length") || str.includes("dtype not specified")) return true;
        return originalStderrWrite(chunk, ...args);
      };
      process.stderr.write = stderrFilter;
      let cg;
      try {
        if (!KiroGraph.isInitialized(cwd)) {
          process.stdout.write("  Downloading embedding model\u2026\n");
          cg = await KiroGraph.init(cwd, void 0, modelProgress);
          process.stdout.write("\n");
          console.log("  \u2713 Created .kirograph/");
        } else {
          cg = await KiroGraph.open(cwd, modelProgress);
          if (fileBytes.size > 0) process.stdout.write("\n");
        }
      } finally {
        process.stderr.write = originalStderrWrite;
      }
      console.log("  Indexing...");
      const result = await cg.indexAll({ onProgress: import_progress.renderIndexProgress });
      process.stdout.write("\n");
      console.log(`  \u2713 Indexed ${result.filesIndexed} files, ${result.nodesCreated} symbols, ${result.edgesCreated} edges`);
      cg.close();
      if (typesenseDashboard) {
        const dashboardServer = await (0, import_dashboard.openTypesenseDashboard)(cwd);
        console.log(`  ${import_ui.dim}Press Ctrl+C to stop the dashboard server when done.${import_ui.reset}`);
        await new Promise((resolve) => {
          process.on("SIGINT", () => {
            if (dashboardServer) {
              dashboardServer.close(() => resolve());
            } else {
              resolve();
            }
          });
        });
        return;
      }
      if (qdrantDashboard) {
        await (0, import_qdrant_dashboard.openQdrantDashboard)(cwd);
      }
    }
    installer.printNextSteps(cwd);
  } finally {
    rl.close();
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  runInstaller
});
//# sourceMappingURL=index.js.map
