import { inferModuleFromEntity } from "./entity-graph.js";
import {
  entityToIndexableRecord,
  computeEntitiesChecksum
} from "./entity-index-config.js";
let lastIndexChecksum = null;
async function indexEntitiesForSearch(searchService, graph, force = false) {
  if (graph.nodes.length === 0) {
    console.error("[Entity Index] No entities to index");
    return { count: 0 };
  }
  const indexedEntities = graph.nodes.map((node) => {
    const relationships = graph.edges.filter((edge) => edge.source === node.className).map((edge) => ({
      relationship: edge.relationship,
      target: edge.target,
      property: edge.property,
      nullable: edge.nullable
    }));
    return {
      className: node.className,
      tableName: node.tableName,
      module: inferModuleFromEntity(node.className, node.tableName),
      fields: node.properties,
      relationships
    };
  });
  const checksum = computeEntitiesChecksum(
    indexedEntities.map((e) => ({
      className: e.className,
      tableName: e.tableName,
      fieldCount: e.fields.length
    }))
  );
  if (!force && lastIndexChecksum === checksum) {
    console.error(`[Entity Index] Skipping indexing - ${indexedEntities.length} entities unchanged`);
    return { count: 0 };
  }
  const records = indexedEntities.map(
    (entity) => entityToIndexableRecord(entity)
  );
  try {
    console.error(`[Entity Index] Starting bulk index of ${records.length} entities...`);
    const timeoutMs = 6e4;
    const indexPromise = searchService.bulkIndex(records);
    const timeoutPromise = new Promise(
      (_, reject) => setTimeout(() => reject(new Error(`Bulk index timed out after ${timeoutMs}ms`)), timeoutMs)
    );
    await Promise.race([indexPromise, timeoutPromise]);
    lastIndexChecksum = checksum;
    console.error(`[Entity Index] Indexed ${records.length} entity schemas for hybrid search`);
    return { count: records.length };
  } catch (error) {
    console.error("[Entity Index] Failed to index entities:", error);
    lastIndexChecksum = checksum;
    return { count: records.length };
  }
}
function clearEntityIndexCache() {
  lastIndexChecksum = null;
}
export {
  clearEntityIndexCache,
  indexEntitiesForSearch
};
//# sourceMappingURL=entity-index.js.map
