"""Ingestion launching: inline (tests/dev) or via a Celery task (production)."""

from __future__ import annotations

import uuid
from collections.abc import Callable

from sqlalchemy.orm import Session

from legate.config import get_settings
from legate.observability.logging import get_logger
from legate.rag.embeddings.factory import build_embedder
from legate.rag.ingestion import ingest_document
from legate.rag.storage import build_storage
from legate.rag.vectorstore.factory import build_vector_store

logger = get_logger(__name__)


def ingest_now(document_id: uuid.UUID, session_factory: Callable[[], Session]) -> None:
    """Run ingestion synchronously in a fresh session (used inline and by the worker)."""
    db = session_factory()
    try:
        ingest_document(
            db=db,
            document_id=document_id,
            embedder=build_embedder(),
            vector_store=build_vector_store(),
            storage=build_storage(),
        )
    finally:
        db.close()


def launch_ingestion(document_id: uuid.UUID, session_factory: Callable[[], Session]) -> None:
    if get_settings().kb_ingest_inline:
        ingest_now(document_id, session_factory)
    else:
        # Dispatch to the Celery worker (requires a broker).
        from legate.workers.tasks import ingest_document_task

        ingest_document_task.delay(str(document_id))
