from fastapi import APIRouter, HTTPException
from session_hub_fastapi.models.session_hub import BackfillResult

from session_hub_core.config import DatabaseConfig, EmbeddingConfig
from session_hub_core.embeddings import EmbeddingService
from session_hub_core.exceptions import SyncError

router = APIRouter(tags=["Embeddings"])


@router.post("/api/embeddings/backfill", response_model=BackfillResult)
async def backfill_embeddings(
    only_sessions: bool = False,
    only_messages: bool = False,
) -> BackfillResult:
    try:
        embedding_config = EmbeddingConfig.from_env()
    except ValueError as exc:
        raise HTTPException(status_code=503, detail="OPENROUTER_API_KEY not configured") from exc
    service = EmbeddingService(DatabaseConfig.from_env(), embedding_config)
    try:
        backfilled = await service.backfill_missing(
            only_sessions=only_sessions, only_messages=only_messages
        )
    except SyncError as exc:
        raise HTTPException(status_code=502, detail=str(exc)) from exc
    finally:
        await service.close()
    return BackfillResult(backfilled=backfilled)
