"""robots.txt checks with caching, built on urllib.robotparser."""

from __future__ import annotations

import time
import urllib.error
import urllib.request
import urllib.robotparser
from typing import Dict, Optional, Tuple
from urllib.parse import urlsplit


class RobotsCache:
    """Fetch and cache robots.txt per origin.

    Behavior follows common practice (and RFC 9309):
    - 4xx (e.g. 404): no restrictions.
    - 5xx or network error: treat the whole site as disallowed for now.
    """

    def __init__(self, user_agent: str, ttl: float = 3600, timeout: float = 10, opener=None):
        self.user_agent = user_agent
        self.ttl = ttl
        self.timeout = timeout
        self._open = opener or urllib.request.urlopen
        self._cache: Dict[str, Tuple[float, Optional[urllib.robotparser.RobotFileParser], bool]] = {}

    @staticmethod
    def origin(url: str) -> str:
        p = urlsplit(url)
        return f"{p.scheme}://{p.netloc}"

    def _load(self, origin: str):
        now = time.time()
        hit = self._cache.get(origin)
        if hit and now - hit[0] < self.ttl:
            return hit[1], hit[2]
        rp = urllib.robotparser.RobotFileParser()
        allow_all = False
        try:
            req = urllib.request.Request(origin + "/robots.txt", headers={"User-Agent": self.user_agent})
            with self._open(req, timeout=self.timeout) as r:
                rp.parse(r.read().decode("utf-8", "replace").splitlines())
        except urllib.error.HTTPError as e:
            if 400 <= e.code < 500:
                allow_all = True
                rp = None
            else:
                rp = None  # server error: disallow
        except (urllib.error.URLError, OSError):
            rp = None
        self._cache[origin] = (now, rp, allow_all)
        return rp, allow_all

    def allowed(self, url: str) -> bool:
        rp, allow_all = self._load(self.origin(url))
        if allow_all:
            return True
        if rp is None:
            return False
        return rp.can_fetch(self.user_agent, url)

    def crawl_delay(self, url: str) -> Optional[float]:
        rp, _ = self._load(self.origin(url))
        if rp is None:
            return None
        d = rp.crawl_delay(self.user_agent)
        return float(d) if d is not None else None

    def sitemaps(self, url: str):
        rp, _ = self._load(self.origin(url))
        return list(rp.site_maps() or []) if rp else []
