"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 lancedb_index_exports = {};
__export(lancedb_index_exports, {
  LanceDBIndex: () => LanceDBIndex
});
module.exports = __toCommonJS(lancedb_index_exports);
var path = __toESM(require("path"));
var import_errors = require("../errors");
const DEFAULT_DIM = 768;
const DB_DIR = "lancedb";
const TABLE_NAME = "kg_nodes";
class LanceDBIndex {
  constructor(kirographDir, dim = DEFAULT_DIM) {
    this.kirographDir = kirographDir;
    this.dim = dim;
    this.db = null;
    this.table = null;
    this._available = false;
    this.dbPath = path.join(kirographDir, DB_DIR);
  }
  isAvailable() {
    return this._available;
  }
  /**
   * Load @lancedb/lancedb, open the file-persisted database, and open or create
   * the kg_nodes table. Silent no-op when the optional dep is missing.
   */
  async initialize() {
    if (this._available) return;
    let lancedb;
    try {
      lancedb = require("@lancedb/lancedb");
    } catch {
      (0, import_errors.logDebug)("LanceDBIndex: @lancedb/lancedb not installed \u2014 LanceDB engine unavailable");
      return;
    }
    try {
      this.db = await lancedb.connect(this.dbPath);
      const existingTables = await this.db.tableNames();
      if (existingTables.includes(TABLE_NAME)) {
        this.table = await this.db.openTable(TABLE_NAME);
      } else {
        this.table = await this.db.createTable(TABLE_NAME, [{
          node_id: "__init__",
          name: "__init__",
          kind: "function",
          file_path: "",
          signature: "",
          vector: new Float32Array(this.dim)
        }]);
        await this.table.delete(`node_id = '__init__'`);
      }
      this._available = true;
      (0, import_errors.logDebug)("LanceDBIndex: ready", { path: this.dbPath, dim: this.dim });
    } catch (err) {
      (0, import_errors.logError)("LanceDBIndex: initialization failed", { error: String(err) });
    }
  }
  /**
   * Insert or update a node using LanceDB's native mergeInsert — a single
   * round-trip that updates the row if node_id exists, inserts it otherwise.
   */
  async upsert(node, embedding) {
    if (!this._available || !this.table) return;
    try {
      await this.table.mergeInsert("node_id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute([{
        node_id: node.id,
        name: node.name,
        kind: node.kind,
        file_path: node.filePath,
        signature: node.signature ?? "",
        vector: embedding
      }]);
    } catch (err) {
      (0, import_errors.logWarn)("LanceDBIndex: upsert failed", { nodeId: node.id, error: String(err) });
    }
  }
  /**
   * Remove a node's record from the index.
   */
  async delete(nodeId) {
    if (!this._available || !this.table) return;
    try {
      await this.table.delete(`node_id = '${nodeId.replace(/'/g, "''")}'`);
    } catch (err) {
      (0, import_errors.logWarn)("LanceDBIndex: delete failed", { nodeId, error: String(err) });
    }
  }
  /**
   * ANN vector search. Returns node IDs ordered by cosine similarity (descending).
   */
  async search(queryVec, topN = 10) {
    if (!this._available || !this.table) return [];
    try {
      const results = await this.table.search(queryVec).distanceType("cosine").limit(topN).toArray();
      return results.map((row) => row.node_id);
    } catch (err) {
      (0, import_errors.logWarn)("LanceDBIndex: search failed", { error: String(err) });
      return [];
    }
  }
  /** Return all node IDs currently stored in the index. */
  async getEmbeddedNodeIds() {
    if (!this._available || !this.table) return [];
    try {
      const rows = await this.table.query().select(["node_id"]).toArray();
      return rows.map((row) => row.node_id);
    } catch {
      return [];
    }
  }
  /** Number of records currently in the index. */
  async count() {
    if (!this._available || !this.table) return 0;
    try {
      return await this.table.countRows();
    } catch {
      return 0;
    }
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  LanceDBIndex
});
//# sourceMappingURL=lancedb-index.js.map
