"""HTTP client with rate limiting and retries."""

from __future__ import annotations

import sys
import time
from typing import Optional
from urllib.parse import urlparse

import httpx


class Fetcher:
    def __init__(self, cfg: dict):
        self.timeout = cfg.get("timeout", 15)
        self.max_retries = cfg.get("max_retries", 2)
        self.retry_delay = cfg.get("retry_delay", 2)
        self.rate_delay = cfg.get("rate_limit_delay", 0.5)
        self.ua = cfg.get("user_agent", "PlatoonBot/1.0")
        self._last_request: dict[str, float] = {}
        self._client = httpx.Client(
            timeout=self.timeout,
            headers={"User-Agent": self.ua},
            follow_redirects=True,
        )

    def _wait(self, domain: str):
        now = time.monotonic()
        last = self._last_request.get(domain, 0)
        gap = now - last
        if gap < self.rate_delay:
            time.sleep(self.rate_delay - gap)
        self._last_request[domain] = time.monotonic()

    def get(self, url: str, **kwargs) -> Optional[httpx.Response]:
        domain = urlparse(url).netloc
        for attempt in range(self.max_retries + 1):
            try:
                self._wait(domain)
                resp = self._client.get(url, **kwargs)
                resp.raise_for_status()
                return resp
            except Exception as e:
                if attempt < self.max_retries:
                    print(f"  [retry {attempt+1}] {url}: {e}", file=sys.stderr)
                    time.sleep(self.retry_delay)
                else:
                    print(f"  [failed] {url}: {e}", file=sys.stderr)
        return None

    def close(self):
        self._client.close()
