# @File: backend/services/uptimerobot/logger.py
# @Desc: Best-effort persistence of UptimeRobot API call logs.
#        Opens a short-lived session and writes an ``UptimeApiLog`` row so
#        the diagnostics page can render call timelines without hammering
#        the UR upstream. All failures here are swallowed — logging must
#        never turn into a denial-of-service vector on the hot path.
import logging
from typing import Optional

from core.database import db_manager
from models.uptimerobot import UptimeApiLog

logger = logging.getLogger(__name__)


async def record_uptimerobot_call(
    *,
    endpoint: str,
    method: str = "GET",
    status: str = "ok",
    http_status: Optional[int] = None,
    duration_ms: Optional[int] = None,
    error_class: Optional[str] = None,
    error_message: Optional[str] = None,
    user_email: Optional[str] = None,
) -> None:
    """Persist a single UptimeRobot API call log row."""
    try:
        if not db_manager.async_session_maker:
            await db_manager.ensure_initialized()
        if not db_manager.async_session_maker:
            return
        async with db_manager.async_session_maker() as session:
            row = UptimeApiLog(
                endpoint=(endpoint or "unknown")[:255],
                method=(method or "GET")[:8],
                status=(status or "ok")[:16],
                http_status=http_status,
                duration_ms=duration_ms,
                error_class=(error_class[:64] if error_class else None),
                error_message=(error_message[:2000] if error_message else None),
                user_email=(user_email or None),
            )
            session.add(row)
            await session.commit()
    except Exception:  # noqa: BLE001 - logging must never break the caller
        logger.exception(
            "Failed to persist uptime_api_logs row for endpoint=%s", endpoint
        )