"""Live R1/R2/R3 alert checks (stateless — rule-based)."""
from __future__ import annotations

from typing import Any

from fastapi import Depends
from sqlalchemy.orm import Session

from ._common import _session, router


@router.get("/api/alerts")
def list_alerts(s: Session = Depends(_session)) -> dict[str, Any]:
    """Run R1/R2/R3 threshold checks against crawl_log/article and return alerts.

    Called live — no persistence layer for alerts in v2 yet (design doc §4.7
    keeps this rule-based + stateless so operators see current status).
    """
    from govcrawler.alerting.checks import run_checks

    alerts = run_checks(session=s)
    by_code: dict[str, int] = {}
    items: list[dict[str, Any]] = []
    for a in alerts:
        by_code[a.code] = by_code.get(a.code, 0) + 1
        items.append({
            "code": a.code,
            "site_code": a.site_code,
            "target_code": a.target_code,
            "message": a.message,
        })
    return {
        "count": len(items),
        "by_code": by_code,
        "items": items,
    }
