#!/usr/bin/env node

// src/symbols/embedder.ts
import path from "path";
import os from "os";
import fs from "fs";
var EMBEDDING_MODEL_ID = "Xenova/paraphrase-multilingual-MiniLM-L12-v2";
var EMBEDDING_DIM = 384;
var pipelinePromise = null;
function cacheDir() {
  return path.join(os.homedir(), ".aicli", "models");
}
async function getEmbedder() {
  if (pipelinePromise) return pipelinePromise;
  pipelinePromise = (async () => {
    const mod = await import("@huggingface/transformers");
    const dir = cacheDir();
    fs.mkdirSync(dir, { recursive: true });
    mod.env.cacheDir = dir;
    mod.env.allowRemoteModels = true;
    mod.env.allowLocalModels = true;
    const pipe = await mod.pipeline("feature-extraction", EMBEDDING_MODEL_ID, {
      // Keep the ONNX session in float32; int8 quantization exists but the
      // quality drop on short code identifiers is noticeable.
      dtype: "fp32"
    });
    return pipe;
  })();
  return pipelinePromise;
}
async function embed(texts) {
  if (texts.length === 0) return [];
  const pipe = await getEmbedder();
  const out = await pipe(texts, { pooling: "mean", normalize: true });
  const batch = texts.length;
  const dim = EMBEDDING_DIM;
  const rows = new Array(batch);
  for (let i = 0; i < batch; i++) {
    rows[i] = new Float32Array(out.data.buffer, out.data.byteOffset + i * dim * 4, dim).slice();
  }
  return rows;
}
async function embedOne(text) {
  const [vec] = await embed([text]);
  return vec;
}

export {
  EMBEDDING_DIM,
  embed,
  embedOne
};
