"""Parse gaiia rate-limit response headers."""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime
from typing import Mapping


@dataclass
class RateLimitInfo:
    allowed: bool | None
    cost: int | None
    limit: int | None
    used: int | None
    remaining: int | None
    retry_at: datetime | None

    @classmethod
    def from_headers(cls, headers: Mapping[str, str]) -> RateLimitInfo:
        def _get(name: str) -> str | None:
            for k, v in headers.items():
                if k.lower() == name.lower():
                    return v
            return None

        def _int(name: str) -> int | None:
            v = _get(name)
            try:
                return int(v) if v is not None else None
            except ValueError:
                return None

        def _bool(name: str) -> bool | None:
            v = _get(name)
            if v is None:
                return None
            return v.strip().lower() == "true"

        def _dt(name: str) -> datetime | None:
            v = _get(name)
            if not v:
                return None
            try:
                return datetime.fromisoformat(v.replace("Z", "+00:00"))
            except ValueError:
                return None

        return cls(
            allowed=_bool("X-Rate-Limit-Allowed"),
            cost=_int("X-Rate-Limit-Cost"),
            limit=_int("X-Rate-Limit-Limit"),
            used=_int("X-Rate-Limit-Used"),
            remaining=_int("X-Rate-Limit-Remaining"),
            retry_at=_dt("X-Rate-Limit-Retry-At") or _dt("X-Rate-Limit-Retry-at"),
        )
