"""
Dashboard Metrics Service
=========================
Small DB-backed counters used by the war-room dashboard.
"""

from sqlalchemy import text

from src.core.logging import get_logger
from src.db.base import get_db_context

logger = get_logger("awoooi.dashboard_metrics")


async def fetch_pending_approval_count() -> int:
    """Read the live HITL backlog from approval_records."""
    try:
        async with get_db_context() as db:
            result = await db.execute(
                text(
                    """
                    SELECT count(*)
                    FROM approval_records
                    WHERE upper(status::text) = 'PENDING'
                    """
                )
            )
            return int(result.scalar_one() or 0)
    except Exception as exc:
        logger.warning("dashboard_pending_approval_count_failed", error=str(exc))
        return 0
