export function cosineSimilarity(a, b) {
  if (!a || !b || a.length !== b.length) return 0;

  let dotProduct = 0;
  let normA = 0;
  let normB = 0;
  for (let i = 0; i < a.length; i++) {
    dotProduct += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }
  const denominator = Math.sqrt(normA) * Math.sqrt(normB);
  return denominator === 0 ? 0 : dotProduct / denominator;
}

export function findTopMatches(queryEmbedding, items, topK = 10) {
  if (!queryEmbedding || !items || items.length === 0) return [];
  const scored = items.map((item) => ({
    id: item.id,
    similarity: cosineSimilarity(queryEmbedding, item.embedding),
  }));
  scored.sort((a, b) => b.similarity - a.similarity);
  return scored.slice(0, topK);
}

export function findMatchesAboveThreshold(queryEmbedding, items, threshold = 0.5) {
  if (!queryEmbedding || !items || items.length === 0) return [];
  const scored = items
    .map((item) => ({
      id: item.id,
      similarity: cosineSimilarity(queryEmbedding, item.embedding),
    }))
    .filter((item) => item.similarity >= threshold);
  scored.sort((a, b) => b.similarity - a.similarity);
  return scored;
}
