/**
 * db/oracle-docs.js — retrieval over the oracle_doc_chunks RAG store.
 *
 * Owns: cosine-similarity search of Oracle documentation chunks embedded by
 *       scripts/ingest-oracle-docs.js (text-embedding-3-small, 1536 dims).
 * Does NOT own: embedding generation (caller supplies the query vector),
 *               ingestion, TuneBot prompt assembly.
 */

'use strict';

const pool = require('./index');

/**
 * Return the top-N most similar doc chunks to a query embedding.
 * Uses cosine distance (<=>) against the ivfflat vector_cosine_ops index.
 *
 * @param {number[]} embedding  — 1536-dim query vector (same model as ingestion)
 * @param {Object}   [opts]
 * @param {number}   [opts.limit=5]      — max chunks to return
 * @param {number}   [opts.minSimilarity=0.3] — drop weak matches (0..1; cosine)
 * @returns {Promise<Array<{doc_name, chunk_index, content, similarity}>>}
 */
async function searchDocChunks(embedding, { limit = 5, minSimilarity = 0.3 } = {}) {
  if (!Array.isArray(embedding) || embedding.length === 0) return [];
  const vec = '[' + embedding.join(',') + ']';
  const { rows } = await pool.query(
    `SELECT doc_name,
            chunk_index,
            content,
            1 - (embedding <=> $1::vector) AS similarity
       FROM oracle_doc_chunks
      ORDER BY embedding <=> $1::vector
      LIMIT $2`,
    [vec, limit]
  );
  return rows.filter(r => Number(r.similarity) >= minSimilarity);
}

module.exports = { searchDocChunks };
