"""
cortex/api/routes/admin/embedding_worker.py — Health endpoint for embedding backfill worker (#1443).

Endpoint:
    GET /api/v1/admin/embedding-worker/status — Worker health + queue stats
"""
from __future__ import annotations

import logging
from typing import Any, Dict

from fastapi import APIRouter, Depends

from cortex.api.deps import PREFIX

logger = logging.getLogger(__name__)

# Holder for the worker instance, set during app startup
backfill_worker_holder: Dict[str, Any] = {}


def _register(router: APIRouter, verify_api_key) -> None:
    """Register embedding worker admin routes."""

    @router.get(
        f"{PREFIX}/admin/embedding-worker/status",
        dependencies=[Depends(verify_api_key)],
        tags=["admin"],
        summary="Embedding backfill worker status",
    )
    async def embedding_worker_status():
        """Return the current state of the embedding backfill worker."""
        worker = backfill_worker_holder.get("worker")
        if worker is None:
            return {
                "running": False,
                "last_scan_at": None,
                "queue": {"pending": 0, "processing": 0, "done": 0, "failed": 0},
                "last_batch": None,
            }

        worker_status = worker.status

        # Get queue stats from the database
        queue_stats = {"pending": 0, "processing": 0, "done": 0, "failed": 0}
        try:
            import aiosqlite
            async with aiosqlite.connect(worker.db_path) as conn:
                conn.row_factory = aiosqlite.Row
                queue_stats = await worker.get_queue_stats(conn)
        except Exception as exc:
            logger.warning("Failed to get backfill queue stats: %s", exc)

        return {
            "running": worker.is_alive,
            "last_scan_at": worker_status.get("last_scan_at"),
            "queue": queue_stats,
            "last_batch": worker_status.get("last_batch"),
        }
