from dataclasses import dataclass
from datetime import datetime

import httpx

from .base import AbuseResponse, json_data, parse_datetime
from .models import ReportInfo


@dataclass(frozen=True, slots=True, kw_only=True)
class CheckResponse(AbuseResponse):
    ip_address: str
    is_public: bool
    ip_version: int
    is_whitelisted: bool | None
    abuse_confidence_score: int
    country_code: str | None
    usage_type: str | None
    isp: str | None
    domain: str | None
    hostnames: tuple[str, ...]
    is_tor: bool
    total_reports: int
    num_distinct_users: int
    last_reported_at: datetime | None
    country_name: str | None
    reports: tuple[ReportInfo, ...]

    @classmethod
    def from_response(cls, response: httpx.Response) -> "CheckResponse":
        data = json_data(response)
        last = data.get("lastReportedAt")
        return cls(
            **cls.metadata(response),
            ip_address=data["ipAddress"],
            is_public=data["isPublic"],
            ip_version=data["ipVersion"],
            is_whitelisted=data.get("isWhitelisted"),
            abuse_confidence_score=data["abuseConfidenceScore"],
            country_code=data.get("countryCode"),
            usage_type=data.get("usageType"),
            isp=data.get("isp"),
            domain=data.get("domain"),
            hostnames=tuple(data.get("hostnames", [])),
            is_tor=data["isTor"],
            total_reports=data["totalReports"],
            num_distinct_users=data["numDistinctUsers"],
            last_reported_at=parse_datetime(last) if last else None,
            country_name=data.get("countryName"),
            reports=tuple(ReportInfo.from_dict(item) for item in data.get("reports", [])),
        )
