// Shared Ollama embed client. Single capped implementation used by every
// process that writes a vector-indexed node outside the memory plugin (admin
// MCP PIN setup, scheduling ICS ingest, UI lazy Person create). The memory
// plugin's `lib/embeddings.ts` re-exports these so there is one cap constant
// and one POST shape across the platform (Task 636). fetch-only — no node:fs —
// so it is safe to bundle into the ESM payload.

const OLLAMA_URL = process.env.OLLAMA_URL ?? "http://localhost:11434";
const EMBED_MODEL = process.env.EMBED_MODEL ?? "nomic-embed-text";

// nomic-embed-text has a 2048-token context (~8k chars at ~4 chars/token).
// An over-limit input makes the Ollama embed endpoint error; cap defensively so
// an oversized body embeds (truncated) instead of throwing and aborting the
// caller.
export const EMBED_INPUT_MAX_CHARS = 8000;

function capInput(text: string): string {
  if (text.length <= EMBED_INPUT_MAX_CHARS) return text;
  process.stderr.write(
    `[embed] op=truncate origBytes=${text.length} cappedBytes=${EMBED_INPUT_MAX_CHARS}\n`,
  );
  return text.slice(0, EMBED_INPUT_MAX_CHARS);
}

export async function embed(text: string): Promise<number[]> {
  const input = capInput(text);
  const res = await fetch(`${OLLAMA_URL}/api/embed`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ model: EMBED_MODEL, input }),
  });
  if (!res.ok) {
    const body = await res.text();
    throw new Error(`Ollama embedding failed (${res.status}): ${body}`);
  }
  const data = (await res.json()) as { embeddings: number[][] };
  return data.embeddings[0];
}

export async function embedBatch(texts: string[]): Promise<number[][]> {
  const input = texts.map(capInput);
  const res = await fetch(`${OLLAMA_URL}/api/embed`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ model: EMBED_MODEL, input }),
  });
  if (!res.ok) {
    const body = await res.text();
    throw new Error(`Ollama batch embedding failed (${res.status}): ${body}`);
  }
  const data = (await res.json()) as { embeddings: number[][] };
  return data.embeddings;
}
