from dataclasses import dataclass
from datetime import datetime

import httpx

from .base import AbuseResponse, parse_datetime
from .models import BlacklistedIP


@dataclass(frozen=True, slots=True, kw_only=True)
class BlacklistResponse(AbuseResponse):
    generated_at: datetime
    blacklisted_ips: tuple[BlacklistedIP, ...]

    @classmethod
    def from_response(cls, response: httpx.Response) -> "BlacklistResponse":
        payload = response.json()
        return cls(
            **cls.metadata(response),
            generated_at=parse_datetime(payload["meta"]["generatedAt"]),
            blacklisted_ips=tuple(BlacklistedIP.from_dict(item) for item in payload["data"]),
        )


@dataclass(frozen=True, slots=True, kw_only=True)
class BlacklistPlaintextResponse(AbuseResponse):
    generated_at: datetime
    addresses: tuple[str, ...]

    @property
    def blacklisted_ips(self) -> tuple[str, ...]:
        return self.addresses

    @classmethod
    def from_response(cls, response: httpx.Response) -> "BlacklistPlaintextResponse":
        generated_at = response.headers.get("X-Generated-At")
        if generated_at is None:
            raise ValueError("Plaintext blacklist response omitted X-Generated-At")
        return cls(
            **cls.metadata(response),
            generated_at=parse_datetime(generated_at),
            addresses=tuple(line.strip() for line in response.text.splitlines() if line.strip()),
        )
