"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var docs_exports = {};
__export(docs_exports, {
  register: () => register
});
module.exports = __toCommonJS(docs_exports);
var import_config = require("../../config");
var import_ui = require("../ui");
function safeCloseAndExit(cg, code = 0) {
  try {
    cg.close();
  } catch {
  }
  try {
    const fs = require("fs");
    if (process.stdout.writableEnded === false) process.stdout.write("");
    if (process.stderr.writableEnded === false) process.stderr.write("");
    fs.closeSync(2);
    fs.closeSync(1);
  } catch {
  }
  process.exit(code);
}
function register(program) {
  const docs = program.command("docs").description("Documentation navigation (requires enableDocs: true)");
  docs.command("toc [file]").description("Print table of contents for a file or the whole project").option("--tree", "Show nested tree structure").option("--json", "Output as JSON").action(async (file, opts) => {
    const cwd = process.cwd();
    const config = await (0, import_config.loadConfig)(cwd);
    if (!config.enableDocs) {
      console.error(`  \u2716 Documentation indexing is not enabled. Set ${import_ui.violet}${import_ui.bold}enableDocs: true${import_ui.reset} in .kirograph/config.json`);
      console.error(`  ${import_ui.dim}Then re-run:${import_ui.reset} ${import_ui.violet}${import_ui.bold}kirograph index${import_ui.reset}`);
      process.exit(1);
    }
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph not initialized. Run: kirograph init");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyDocsSchema();
    const { DocsQueries } = await Promise.resolve().then(() => require("../../docs/queries.js"));
    const queries = new DocsQueries(db.getRawDb(), cwd);
    const toc = queries.getToc({ file, tree: opts.tree });
    if (toc.length === 0) {
      console.log(`  ${import_ui.dim}No documentation sections found.${import_ui.reset} Run ${import_ui.violet}${import_ui.bold}kirograph index${import_ui.reset} first.`);
      cg.close();
      return;
    }
    if (opts.json) {
      console.log(JSON.stringify(toc, null, 2));
    } else {
      for (const entry of toc) {
        const prefix = "#".repeat(entry.level || 1);
        const summary = entry.summary ? ` ${import_ui.dim}\u2014 ${entry.summary}${import_ui.reset}` : "";
        console.log(`  ${prefix} ${import_ui.bold}${entry.title}${import_ui.reset}${summary}`);
        console.log(`    ${import_ui.dim}${entry.id}${import_ui.reset}`);
      }
    }
    cg.close();
  });
  docs.command("search <query>").description("Search documentation sections").option("--file <path>", "Narrow search to a specific file").option("--limit <n>", "Max results", "10").option("--json", "Output as JSON").action(async (query, opts) => {
    const cwd = process.cwd();
    const config = await (0, import_config.loadConfig)(cwd);
    if (!config.enableDocs) {
      console.error(`  \u2716 Documentation indexing is not enabled. Set ${import_ui.violet}${import_ui.bold}enableDocs: true${import_ui.reset} in .kirograph/config.json`);
      process.exit(1);
    }
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph not initialized.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyDocsSchema();
    const { DocsQueries } = await Promise.resolve().then(() => require("../../docs/queries.js"));
    const queries = new DocsQueries(db.getRawDb(), cwd, config);
    const results = await queries.searchSections(query, { file: opts.file, limit: parseInt(opts.limit ?? "10", 10) });
    if (results.length === 0) {
      console.log(`  ${import_ui.dim}No sections found matching "${query}".${import_ui.reset}`);
      cg.close();
      return;
    }
    if (opts.json) {
      console.log(JSON.stringify(results, null, 2));
    } else {
      for (const r of results) {
        const summary = r.section.summary ? `
    ${import_ui.dim}${r.section.summary}${import_ui.reset}` : "";
        console.log(`  ${import_ui.green}\u25CF${import_ui.reset} ${import_ui.bold}${r.section.title}${import_ui.reset} ${import_ui.dim}[${r.section.filePath}]${import_ui.reset}${summary}`);
        console.log(`    ${import_ui.dim}ID: ${r.section.id}${import_ui.reset}`);
      }
    }
    cg.close();
  });
  docs.command("section <id>").description("Print full content of a section by ID").option("--context", "Include ancestor headings and child summaries").action(async (id, opts) => {
    const cwd = process.cwd();
    const config = await (0, import_config.loadConfig)(cwd);
    if (!config.enableDocs) {
      console.error(`  \u2716 Documentation indexing is not enabled. Set ${import_ui.violet}${import_ui.bold}enableDocs: true${import_ui.reset} in .kirograph/config.json`);
      process.exit(1);
    }
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph not initialized.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyDocsSchema();
    const { DocsQueries } = await Promise.resolve().then(() => require("../../docs/queries.js"));
    const queries = new DocsQueries(db.getRawDb(), cwd);
    const result = queries.getSection(id, { context: opts.context });
    if (!result) {
      const rawDb = db.getRawDb();
      const idParts = id.split("::");
      const filePath = idParts[0] ?? "";
      const searchSlug = (idParts[1] ?? "").replace(/#\d+$/, "").split("/").pop() ?? "";
      let suggestions = [];
      if (searchSlug) {
        suggestions = rawDb.all(
          `SELECT id, title FROM doc_sections WHERE file_path = ? AND id LIKE ? LIMIT 5`,
          [filePath, `%${searchSlug}%`]
        );
      }
      if (suggestions.length === 0 && filePath) {
        suggestions = rawDb.all(
          `SELECT id, title FROM doc_sections WHERE file_path = ? ORDER BY position LIMIT 5`,
          [filePath]
        );
      }
      console.error(`  \u2716 Section "${id}" not found.`);
      if (suggestions.length > 0) {
        console.error(`
  ${import_ui.dim}Did you mean:${import_ui.reset}`);
        for (const s of suggestions) {
          console.error(`    ${s.id}  ${import_ui.dim}(${s.title})${import_ui.reset}`);
        }
      } else {
        console.error(`
  ${import_ui.dim}Use ${import_ui.violet}kirograph docs toc${import_ui.reset}${import_ui.dim} to list available section IDs.${import_ui.reset}`);
      }
      safeCloseAndExit(cg, 1);
    }
    if (result.ancestors?.length) {
      console.log(`  ${import_ui.dim}${result.ancestors.map((a) => a.title).join(" > ")} > ${result.section.title}${import_ui.reset}
`);
    }
    console.log(result.content);
    if (result.children?.length) {
      console.log(`
  ${import_ui.dim}Child sections:${import_ui.reset}`);
      for (const child of result.children) {
        const summary = child.summary ? ` \u2014 ${child.summary}` : "";
        console.log(`    ${import_ui.dim}\u2022${import_ui.reset} ${child.title}${summary}`);
      }
    }
    cg.close();
  });
  docs.command("outline <file>").description("Print heading hierarchy for a document").action(async (file) => {
    const cwd = process.cwd();
    const config = await (0, import_config.loadConfig)(cwd);
    if (!config.enableDocs) {
      console.error(`  \u2716 Documentation indexing is not enabled. Set ${import_ui.violet}${import_ui.bold}enableDocs: true${import_ui.reset} in .kirograph/config.json`);
      process.exit(1);
    }
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph not initialized.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyDocsSchema();
    const { DocsQueries } = await Promise.resolve().then(() => require("../../docs/queries.js"));
    const queries = new DocsQueries(db.getRawDb(), cwd);
    const outline = queries.getOutline(file);
    if (outline.length === 0) {
      console.log(`  ${import_ui.dim}No sections found in "${file}".${import_ui.reset}`);
      cg.close();
      return;
    }
    console.log(`
  ${import_ui.bold}${file}${import_ui.reset}
`);
    const render = (entries, indent) => {
      for (const entry of entries) {
        const summary = entry.summary ? ` ${import_ui.dim}\u2014 ${entry.summary}${import_ui.reset}` : "";
        console.log(`${indent}  ${"#".repeat(entry.level || 1)} ${entry.title}${summary}`);
        if (entry.children?.length) render(entry.children, indent + "  ");
      }
    };
    render(outline, "");
    cg.close();
  });
  docs.command("refs <id>").description("Show code \u2194 doc cross-references").action(async (id) => {
    const cwd = process.cwd();
    const config = await (0, import_config.loadConfig)(cwd);
    if (!config.enableDocs) {
      console.error(`  \u2716 Documentation indexing is not enabled. Set ${import_ui.violet}${import_ui.bold}enableDocs: true${import_ui.reset} in .kirograph/config.json`);
      process.exit(1);
    }
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph not initialized.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyDocsSchema();
    const { DocsQueries } = await Promise.resolve().then(() => require("../../docs/queries.js"));
    const queries = new DocsQueries(db.getRawDb(), cwd);
    let refs = queries.getRefs({ sectionId: id });
    if (refs.length === 0) {
      refs = queries.getRefs({ qualifiedName: id });
    }
    if (refs.length === 0) {
      console.log(`  ${import_ui.dim}No cross-references found for "${id}".${import_ui.reset}`);
      cg.close();
      return;
    }
    for (const r of refs) {
      console.log(`  [${r.refType}] ${r.qualifiedName} ${import_ui.dim}(confidence: ${r.confidence.toFixed(2)})${import_ui.reset}`);
    }
    cg.close();
  });
  docs.command("reindex").description("Force re-index all documentation files").action(async () => {
    const cwd = process.cwd();
    const config = await (0, import_config.loadConfig)(cwd);
    if (!config.enableDocs) {
      console.error(`  \u2716 Documentation indexing is not enabled. Set ${import_ui.violet}${import_ui.bold}enableDocs: true${import_ui.reset} in .kirograph/config.json`);
      process.exit(1);
    }
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph not initialized.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyDocsSchema();
    const { DocsIndexer } = await Promise.resolve().then(() => require("../../docs/indexer.js"));
    const indexer = new DocsIndexer(db.getRawDb(), config, cwd);
    console.log(`  ${import_ui.dim}Re-indexing documentation...${import_ui.reset}`);
    const result = await indexer.indexAll({ force: true, onProgress: (msg) => console.log(`  ${import_ui.dim}${msg}${import_ui.reset}`) });
    console.log(`  ${import_ui.green}\u2713${import_ui.reset} ${(0, import_ui.value)(String(result.filesIndexed))} ${import_ui.dim}files,${import_ui.reset} ${(0, import_ui.value)(String(result.sectionsCreated))} ${import_ui.dim}sections created,${import_ui.reset} ${(0, import_ui.value)(String(result.sectionsUpdated))} ${import_ui.dim}updated,${import_ui.reset} ${(0, import_ui.value)(String(result.sectionsRemoved))} ${import_ui.dim}removed${import_ui.reset} ${import_ui.dim}(${result.duration}ms)${import_ui.reset}`);
    if (result.errors.length) {
      console.warn(`  \x1B[33m\u26A0 ${result.errors.length} error(s)\x1B[0m`);
      for (const err of result.errors.slice(0, 5)) console.warn(`    ${err}`);
    }
    cg.close();
  });
  docs.command("lint").description("Find broken refs, stale sections, FTS desync").action(async () => {
    const cwd = process.cwd();
    const config = await (0, import_config.loadConfig)(cwd);
    if (!config.enableDocs) {
      console.error(`  \u2716 Documentation indexing is not enabled. Set ${import_ui.violet}${import_ui.bold}enableDocs: true${import_ui.reset} in .kirograph/config.json`);
      process.exit(1);
    }
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph not initialized.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyDocsSchema();
    const { docsLint } = await Promise.resolve().then(() => require("../../docs/lint.js"));
    const result = docsLint(db.getRawDb(), cwd);
    if (result.totalIssues === 0) {
      console.log(`  ${import_ui.green}\u2713${import_ui.reset} No issues found.`);
      cg.close();
      return;
    }
    console.log(`  Found ${result.totalIssues} issue(s):
`);
    if (result.brokenRefs.length > 0) {
      console.log(`  ${import_ui.bold}Broken code refs:${import_ui.reset} ${result.brokenRefs.length}`);
      for (const ref of result.brokenRefs.slice(0, 10)) {
        console.log(`    ${import_ui.dim}${ref.sectionId} \u2192 ${ref.qualifiedName}${import_ui.reset}`);
      }
      if (result.brokenRefs.length > 10) console.log(`    ${import_ui.dim}\u2026and ${result.brokenRefs.length - 10} more${import_ui.reset}`);
    }
    if (result.staleSections.length > 0) {
      console.log(`  ${import_ui.bold}Stale sections:${import_ui.reset} ${result.staleSections.length}`);
      for (const s of result.staleSections.slice(0, 10)) {
        console.log(`    ${import_ui.dim}${s.filePath} \u2014 ${s.id}${import_ui.reset}`);
      }
      if (result.staleSections.length > 10) console.log(`    ${import_ui.dim}\u2026and ${result.staleSections.length - 10} more${import_ui.reset}`);
    }
    if (result.ftsDesync) {
      console.log(`  ${import_ui.bold}FTS desync:${import_ui.reset} ${result.ftsDesync.sections} sections vs ${result.ftsDesync.ftsRows} FTS rows`);
    }
    if (result.orphanRefs > 0) {
      console.log(`  ${import_ui.bold}Orphan refs:${import_ui.reset} ${result.orphanRefs}`);
    }
    console.log(`
  ${import_ui.dim}Run ${import_ui.violet}${import_ui.bold}kirograph docs reindex${import_ui.reset}${import_ui.dim} to fix stale sections.${import_ui.reset}`);
    cg.close();
  });
  docs.command("reembed").description("Re-embed all doc sections with the current model").action(async () => {
    const cwd = process.cwd();
    const config = await (0, import_config.loadConfig)(cwd);
    if (!config.enableDocs) {
      console.error(`  \u2716 Documentation indexing is not enabled. Set ${import_ui.violet}${import_ui.bold}enableDocs: true${import_ui.reset} in .kirograph/config.json`);
      process.exit(1);
    }
    if (!config.enableEmbeddings) {
      console.error(`  \u2716 Embeddings are not enabled. Set ${import_ui.violet}${import_ui.bold}enableEmbeddings: true${import_ui.reset} in .kirograph/config.json`);
      process.exit(1);
    }
    const KiroGraph = (await Promise.resolve().then(() => require("../../index.js"))).default;
    if (!KiroGraph.isInitialized(cwd)) {
      console.error("  \u2716 KiroGraph not initialized.");
      process.exit(1);
    }
    const cg = await KiroGraph.open(cwd);
    const db = cg.getDatabase();
    db.applyDocsSchema();
    const rawDb = db.getRawDb();
    const sections = rawDb.all("SELECT id, title, summary FROM doc_sections");
    if (sections.length === 0) {
      console.log(`  ${import_ui.dim}No doc sections to embed. Run ${import_ui.violet}${import_ui.bold}kirograph docs reindex${import_ui.reset}${import_ui.dim} first.${import_ui.reset}`);
      cg.close();
      return;
    }
    console.log(`  ${import_ui.dim}Re-embedding ${sections.length} doc sections...${import_ui.reset}`);
    const { DocsVectorManager } = await Promise.resolve().then(() => require("../../docs/vectors.js"));
    const vectorMgr = new DocsVectorManager(config, rawDb);
    const embedded = await vectorMgr.reembed();
    console.log(`  ${import_ui.green}\u2713${import_ui.reset} Embedded ${(0, import_ui.value)(String(embedded))} doc sections with model ${import_ui.dim}${config.embeddingModel}${import_ui.reset}`);
    cg.close();
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  register
});
//# sourceMappingURL=docs.js.map
