"""Outgoing HTTP with SSRF protection (TZ 2.9.8): images by URL, webhooks, introspection.

DNS is resolved up front, private/special ranges are refused, the connection goes to the vetted IP with
SNI / certificate check against the original host name (DNS-rebinding safe); redirects are re-checked.
"""

from __future__ import annotations

import ipaddress
import logging
import socket
from dataclasses import dataclass
from urllib.parse import urljoin, urlsplit

import urllib3
from django.conf import settings

log = logging.getLogger("snapfile.security")

_BLOCKED = [
    ipaddress.ip_network(n)
    for n in (
        "0.0.0.0/8",
        "10.0.0.0/8",
        "100.64.0.0/10",
        "127.0.0.0/8",
        "169.254.0.0/16",
        "172.16.0.0/12",
        "192.168.0.0/16",
        "::1/128",
        "fc00::/7",
        "fe80::/10",
        "::ffff:0:0/96",
    )
]


class FetchError(Exception):
    def __init__(self, code: str, message: str) -> None:
        super().__init__(message)
        self.code = code


@dataclass
class FetchResult:
    status: int
    data: bytes
    content_type: str
    url: str


def _check_ip(ip: str) -> None:
    if getattr(settings, "SNAPFILE_ALLOW_PRIVATE_NETWORK", False):
        return
    addr = ipaddress.ip_address(ip)
    if any(addr in net for net in _BLOCKED) or addr.is_multicast or addr.is_reserved:
        raise FetchError("SSRF_BLOCKED", f"Address {ip} is not allowed")


def _resolve(host: str, port: int) -> str:
    try:
        infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
    except socket.gaierror as exc:
        raise FetchError("DNS_FAILED", f"Cannot resolve {host}") from exc
    addrs = [info[4][0] for info in infos]
    for ip in addrs:
        _check_ip(ip)
    return addrs[0]


def request(
    method: str,
    url: str,
    *,
    body: bytes | None = None,
    headers: dict[str, str] | None = None,
    timeout: float = 5.0,
    max_bytes: int = 10 * 1024 * 1024,
    max_redirects: int = 3,
) -> FetchResult:
    allow_http = getattr(settings, "ALLOW_HTTP_FETCH", False)
    for _ in range(max_redirects + 1):
        parts = urlsplit(url)
        if parts.scheme not in ("https", "http") or (parts.scheme == "http" and not allow_http):
            raise FetchError("SSRF_BLOCKED", "Only https URLs are allowed")
        host = parts.hostname or ""
        port = parts.port or (443 if parts.scheme == "https" else 80)
        if port not in (80, 443) and not getattr(settings, "SNAPFILE_ALLOW_PRIVATE_NETWORK", False):
            raise FetchError("SSRF_BLOCKED", "Only ports 80/443 are allowed")
        ip = _resolve(host, port)
        hdrs = {"Host": parts.netloc, "User-Agent": "Snapfile/1.0", **(headers or {})}
        path = parts.path or "/"
        if parts.query:
            path += "?" + parts.query
        tm = urllib3.Timeout(connect=min(2.0, timeout), read=timeout)
        if parts.scheme == "https":
            pool: urllib3.HTTPConnectionPool = urllib3.HTTPSConnectionPool(
                ip, port, server_hostname=host, assert_hostname=host, timeout=tm, retries=False
            )
        else:
            pool = urllib3.HTTPConnectionPool(ip, port, timeout=tm, retries=False)
        try:
            resp = pool.urlopen(method, path, body=body, headers=hdrs, redirect=False, preload_content=False)
        except urllib3.exceptions.HTTPError as exc:
            raise FetchError("FETCH_FAILED", f"{type(exc).__name__}: {exc}") from exc
        try:
            if resp.status in (301, 302, 303, 307, 308) and resp.headers.get("Location"):
                url = urljoin(url, resp.headers["Location"])
                if resp.status == 303:
                    method, body = "GET", None
                continue
            length = int(resp.headers.get("Content-Length") or 0)
            if length > max_bytes:
                raise FetchError("FETCH_TOO_LARGE", "Response is too large")
            chunks = []
            total = 0
            for chunk in resp.stream(65536):
                total += len(chunk)
                if total > max_bytes:
                    raise FetchError("FETCH_TOO_LARGE", "Response is too large")
                chunks.append(chunk)
            log.info("outgoing request", extra={"event": "http.out", "host": host, "status": resp.status})
            return FetchResult(resp.status, b"".join(chunks), resp.headers.get("Content-Type", ""), url)
        finally:
            resp.release_conn()
    raise FetchError("FETCH_FAILED", "Too many redirects")
