"""Tiny HTTP helpers around urllib.request: timeout + one retry, JSON or text."""
import json
import time
import urllib.request
from typing import Any

TIMEOUT_SECONDS = 30
RETRY_DELAY_SECONDS = 5


class HTTPError(Exception):
    pass


def _fetch_bytes(url: str) -> bytes:
    last_exc: Exception = HTTPError(f"no attempts made for {url}")
    for attempt in (1, 2):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "critmatic-patch-watcher/0.1"})
            with urllib.request.urlopen(req, timeout=TIMEOUT_SECONDS) as resp:
                return resp.read()
        except Exception as exc:
            last_exc = exc
            if attempt == 1:
                time.sleep(RETRY_DELAY_SECONDS)
    raise HTTPError(f"failed to fetch {url}: {last_exc}") from last_exc


def fetch_json(url: str) -> Any:
    return json.loads(_fetch_bytes(url).decode("utf-8"))


def fetch_text(url: str) -> str:
    return _fetch_bytes(url).decode("utf-8")
