/**
 * Dense-vector helpers for face / embedding work.
 *
 * Vectors are plain readonly number arrays — pg returns DOUBLE PRECISION[]
 * columns as JS numbers, and Postgres array literals serialize from JS arrays
 * straight through node-postgres.
 */

export function cosineSimilarity(a: readonly number[], b: readonly number[]): number {
  if (a.length === 0 || a.length !== b.length) return 0;
  let dot = 0;
  let na = 0;
  let nb = 0;
  for (let i = 0; i < a.length; i++) {
    const ai = a[i] ?? 0;
    const bi = b[i] ?? 0;
    dot += ai * bi;
    na += ai * ai;
    nb += bi * bi;
  }
  const denom = Math.sqrt(na) * Math.sqrt(nb);
  if (denom === 0) return 0;
  return dot / denom;
}

export function meanVector(vectors: ReadonlyArray<readonly number[]>): readonly number[] {
  if (vectors.length === 0) return [];
  const first = vectors[0];
  if (!first) return [];
  const dim = first.length;
  const acc = new Array<number>(dim).fill(0);
  for (const v of vectors) {
    if (v.length !== dim) continue;
    for (let i = 0; i < dim; i++) acc[i] = (acc[i] ?? 0) + (v[i] ?? 0);
  }
  for (let i = 0; i < dim; i++) acc[i] = (acc[i] ?? 0) / vectors.length;
  return acc;
}
