-- Deploy schemas/rag/procedures/export_embeddings_csv to pg
-- made with <3 @ constructive.io

-- requires: rag-core

BEGIN;

CREATE FUNCTION rag.export_embeddings_csv(
  p_collection_id uuid,
  p_model_name text DEFAULT NULL
) RETURNS TABLE (
  chunk_id uuid,
  document_id uuid,
  model_name text,
  content text,
  vector_text text
)
LANGUAGE plpgsql
STABLE
AS $$
BEGIN
  RETURN QUERY
  SELECT 
    c.id AS chunk_id,
    c.document_id,
    em.name AS model_name,
    c.content,
    e.vector::text AS vector_text
  FROM rag.embedding e
  JOIN rag.chunk c ON c.id = e.chunk_id
  JOIN rag.document d ON d.id = c.document_id
  JOIN rag.embedding_model em ON em.id = e.model_id
  WHERE d.collection_id = p_collection_id
    AND (p_model_name IS NULL OR em.name = p_model_name)
  ORDER BY d.id, c.chunk_index;
END;
$$;

COMMENT ON FUNCTION rag.export_embeddings_csv(uuid, text) IS 'Export embeddings in CSV-friendly format for a collection';

COMMIT;
