"""REST API rate limit utilization check for heartbeat monitoring."""

from __future__ import annotations

import contextlib
import logging
from pathlib import Path

logger = logging.getLogger("health-heartbeat")

# Track consecutive high-utilization checks for LOUD alert (D-22)
_SUSTAINED_HIGH_COUNT_FILE = Path("/var/tmp/opendeviationbar-ratelimit-sustained.txt")
_SUSTAINED_THRESHOLD = 3  # 3 consecutive checks at 90%+ = LOUD alert
_ALERT_THRESHOLD = 0.90  # 90% of total budget


def check_ratelimit(results: dict[str, bool | str]) -> None:
    """Check aggregate REST API utilization across all consumers (D-22, D-24).

    ``ratelimit_ok`` is a boolean and participates in the healthy gate.
    A sustained >90% utilization means 429 bans are imminent -- flag as UNHEALTHY.
    """
    try:
        from opendeviationbar.ratelimit import RateLimitCoordinator

        coord = RateLimitCoordinator()
        state = coord.get_state()
    except Exception:
        # Rate limit module not available -- not a health issue
        results["ratelimit_ok"] = True
        results["ratelimit_status"] = "unavailable"
        return

    consumers = state.get("consumers", {})
    aggregate = sum(c.get("weight_used", 0) for c in consumers.values())
    budget_total = 6000
    utilization = aggregate / budget_total if budget_total > 0 else 0.0

    # Per-consumer breakdown (D-22)
    for consumer_id in ("sidecar", "kintsugi", "seeder"):
        weight = consumers.get(consumer_id, {}).get("weight_used", 0)
        results[f"ratelimit_{consumer_id}_weight"] = str(weight)

    results["ratelimit_aggregate"] = str(aggregate)
    results["ratelimit_utilization"] = f"{utilization:.1%}"

    # Also read this process's own rate limiter status (Rust singleton)
    try:
        from opendeviationbar._core import get_rest_rate_limiter_status

        local_status = get_rest_rate_limiter_status()
        results["ratelimit_local_utilization"] = f"{local_status.get('utilization', 0):.1%}"
    except Exception:
        pass

    # Sustained high utilization check (D-22)
    if utilization >= _ALERT_THRESHOLD:
        count = _load_sustained_count() + 1
        _save_sustained_count(count)
        if count >= _SUSTAINED_THRESHOLD:
            results["ratelimit_ok"] = False
            results["ratelimit_alert"] = f"SUSTAINED {utilization:.0%} for {count} checks"
            return
    else:
        _save_sustained_count(0)  # reset on drop below threshold

    results["ratelimit_ok"] = True


def _load_sustained_count() -> int:
    try:
        return int(_SUSTAINED_HIGH_COUNT_FILE.read_text().strip())
    except (FileNotFoundError, ValueError, OSError):
        return 0


def _save_sustained_count(count: int) -> None:
    with contextlib.suppress(OSError):
        _SUSTAINED_HIGH_COUNT_FILE.write_text(str(count))
