"""A polite HTTP fetcher: identifies itself, respects robots.txt, rate-limits per host,
retries transient errors with backoff, and caps response size."""

from __future__ import annotations

import gzip
import time
import urllib.error
import urllib.request
from dataclasses import dataclass, field
from typing import Dict, Optional
from urllib.parse import urlsplit

from .robots import RobotsCache

DEFAULT_UA = "llmscrape/0.1 (+https://github.com/Ralpberry-Labs)"


@dataclass
class FetchResult:
    url: str
    status: int
    content_type: str
    text: str
    headers: Dict[str, str] = field(default_factory=dict)
    skipped: str = ""  # reason if not fetched

    @property
    def ok(self) -> bool:
        return not self.skipped and 200 <= self.status < 300


class PoliteFetcher:
    def __init__(self, user_agent: str = DEFAULT_UA, min_delay: float = 1.0, max_bytes: int = 5_000_000,
                 retries: int = 2, timeout: float = 20, respect_robots: bool = True, opener=None,
                 sleep=time.sleep, clock=time.monotonic):
        self.ua = user_agent
        self.min_delay = min_delay
        self.max_bytes = max_bytes
        self.retries = retries
        self.timeout = timeout
        self._open = opener or urllib.request.urlopen
        self.robots = RobotsCache(user_agent, opener=self._open) if respect_robots else None
        self._last: Dict[str, float] = {}
        self._sleep, self._clock = sleep, clock

    def _wait_turn(self, url: str) -> None:
        host = urlsplit(url).netloc
        delay = self.min_delay
        if self.robots:
            cd = self.robots.crawl_delay(url)
            if cd:
                delay = max(delay, cd)
        last = self._last.get(host)
        if last is not None:
            remaining = delay - (self._clock() - last)
            if remaining > 0:
                self._sleep(remaining)
        self._last[host] = self._clock()

    def get(self, url: str) -> FetchResult:
        if urlsplit(url).scheme not in ("http", "https"):
            return FetchResult(url, 0, "", "", skipped="unsupported scheme")
        if self.robots and not self.robots.allowed(url):
            return FetchResult(url, 0, "", "", skipped="disallowed by robots.txt")
        attempt = 0
        while True:
            self._wait_turn(url)
            req = urllib.request.Request(url, headers={
                "User-Agent": self.ua,
                "Accept": "text/html,application/xhtml+xml;q=0.9,text/plain;q=0.8,*/*;q=0.5",
                "Accept-Encoding": "gzip",
            })
            try:
                with self._open(req, timeout=self.timeout) as r:
                    raw = r.read(self.max_bytes + 1)
                    headers = {k.lower(): v for k, v in r.headers.items()}
                    status = getattr(r, "status", 200)
                    final_url = r.geturl() if hasattr(r, "geturl") else url
                if len(raw) > self.max_bytes:
                    return FetchResult(url, status, headers.get("content-type", ""), "", headers,
                                       skipped="response too large")
                if headers.get("content-encoding") == "gzip":
                    raw = gzip.decompress(raw)
                ctype = headers.get("content-type", "")
                charset = "utf-8"
                if "charset=" in ctype:
                    charset = ctype.split("charset=")[-1].split(";")[0].strip() or "utf-8"
                try:
                    text = raw.decode(charset, "replace")
                except LookupError:
                    text = raw.decode("utf-8", "replace")
                return FetchResult(final_url, status, ctype, text, headers)
            except urllib.error.HTTPError as e:
                e.close()
                retryable = e.code in (429, 500, 502, 503, 504)
                if retryable and attempt < self.retries:
                    retry_after = e.headers.get("Retry-After") if e.headers else None
                    wait = float(retry_after) if retry_after and retry_after.isdigit() else 2 ** attempt * 2
                    self._sleep(min(wait, 60))
                    attempt += 1
                    continue
                return FetchResult(url, e.code, "", "", skipped=f"HTTP {e.code}")
            except (urllib.error.URLError, OSError) as e:
                if attempt < self.retries:
                    self._sleep(2 ** attempt * 2)
                    attempt += 1
                    continue
                return FetchResult(url, 0, "", "", skipped=f"network error: {e}")
