"""Native Codex account rate-limit normalization for device display.

Pure functions only. The gateway never derives quota from token accounting,
rollout files or desktop UI scraping; it forwards what the native
``account/rateLimits/read`` response reports.

Everything here is account-level usage data. Account identity, plan type,
credits balance and reset-credit detail are deliberately dropped: the device
only ever receives a remaining percentage, a reset timestamp and a window
duration.
"""
from __future__ import annotations

from dataclasses import dataclass
from typing import Any

# The metered bucket the wearable represents. Unknown buckets are ignored so a
# future backend bucket cannot silently become the Codex quota row.
CODEX_LIMIT_ID = "codex"


@dataclass(frozen=True)
class CodexQuota:
    """Bounded, device-safe view of the Codex account rate limit."""

    valid: bool = False
    remaining_percent: int = 0
    resets_at: int | None = None
    window_minutes: int | None = None

    def wire(self) -> dict[str, Any]:
        return {
            "codex_quota_valid": self.valid,
            "codex_remaining_percent": self.remaining_percent,
            "codex_resets_at": self.resets_at,
            "codex_window_minutes": self.window_minutes,
        }


INVALID = CodexQuota()


def _window_remaining(window: Any) -> int | None:
    """Remaining percentage for one window, or None when unusable."""
    if not isinstance(window, dict):
        return None
    used = window.get("usedPercent")
    # bool is an int subclass; reject it explicitly rather than coercing.
    if isinstance(used, bool) or not isinstance(used, (int, float)):
        return None
    return max(0, min(100, int(round(100 - used))))


def _window_reset(window: dict) -> int | None:
    value = window.get("resetsAt")
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return None
    return int(value)


def _window_minutes(window: dict) -> int | None:
    value = window.get("windowDurationMins")
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return None
    return int(value)


def select_window(snapshot: Any) -> dict | None:
    """Pick the tightest window, matching the single wearable row.

    ``primary``/``secondary`` are both considered. The window with the smaller
    remaining percentage wins; ties break to the earlier valid reset, so the
    device reports the quota it will hit first. A single window is used as-is.
    """
    if not isinstance(snapshot, dict):
        return None
    candidates: list[dict] = []
    for key in ("primary", "secondary"):
        window = snapshot.get(key)
        if not isinstance(window, dict):
            continue
        remaining = _window_remaining(window)
        if remaining is None:
            continue
        candidates.append({"remaining": remaining, "reset": _window_reset(window),
                           "minutes": _window_minutes(window)})
    if not candidates:
        return None
    if len(candidates) == 1:
        return candidates[0]
    return min(candidates, key=lambda item: (
        item["remaining"],
        item["reset"] if item["reset"] is not None else float("inf"),
    ))


def select_snapshot(payload: Any) -> dict | None:
    """Choose the Codex bucket from a ``rateLimits/read`` response.

    ``rateLimitsByLimitId["codex"]`` is authoritative. The backward-compatible
    ``rateLimits`` field is only accepted when its own ``limitId`` is absent or
    explicitly ``codex``: a differently labeled bucket must not be displayed as
    Codex usage.
    """
    if not isinstance(payload, dict):
        return None
    buckets = payload.get("rateLimitsByLimitId")
    if isinstance(buckets, dict):
        bucket = buckets.get(CODEX_LIMIT_ID)
        if isinstance(bucket, dict):
            return bucket
    fallback = payload.get("rateLimits")
    if isinstance(fallback, dict):
        limit_id = fallback.get("limitId")
        if limit_id is None or limit_id == CODEX_LIMIT_ID:
            return fallback
    return None


def normalize(payload: Any) -> CodexQuota:
    """Full ``rateLimits/read`` response -> bounded device view."""
    window = select_window(select_snapshot(payload))
    if window is None:
        return INVALID
    return CodexQuota(valid=True, remaining_percent=window["remaining"],
                      resets_at=window["reset"], window_minutes=window["minutes"])


def normalize_notification(payload: Any) -> CodexQuota:
    """Sparse ``account/rateLimits/updated`` payload -> bounded device view.

    The notification carries the same snapshot shape minus account metadata, so
    it is normalized identically. Absent windows stay invalid rather than
    clearing a previously observed value; the caller refreshes to be safe.
    """
    if not isinstance(payload, dict):
        return INVALID
    snapshot = payload.get("rateLimits")
    window = select_window(snapshot)
    if window is None:
        return INVALID
    return CodexQuota(valid=True, remaining_percent=window["remaining"],
                      resets_at=window["reset"], window_minutes=window["minutes"])