from collections.abc import Mapping
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, cast

import httpx


def parse_datetime(value: str) -> datetime:
    return datetime.fromisoformat(value.replace("Z", "+00:00"))


def json_data(response: httpx.Response) -> Mapping[str, Any]:
    payload = response.json()
    return cast(Mapping[str, Any], payload["data"])


def optional_int_header(response: httpx.Response, name: str) -> int | None:
    value = response.headers.get(name)
    return int(value) if value is not None else None


@dataclass(frozen=True, slots=True, kw_only=True)
class AbuseResponse:
    status_code: int
    content_type: str | None
    cache_control: str | None
    x_ratelimit_limit: int | None
    x_ratelimit_remaining: int | None
    cf_cache_status: str | None
    raw_response: httpx.Response = field(repr=False, compare=False)

    @classmethod
    def metadata(cls, response: httpx.Response) -> dict[str, Any]:
        return {
            "status_code": response.status_code,
            "content_type": response.headers.get("Content-Type"),
            "cache_control": response.headers.get("Cache-Control"),
            "x_ratelimit_limit": optional_int_header(response, "X-RateLimit-Limit"),
            "x_ratelimit_remaining": optional_int_header(response, "X-RateLimit-Remaining"),
            "cf_cache_status": response.headers.get("CF-Cache-Status"),
            "raw_response": response,
        }
