"""HTTP on the client and the upstream side: take requests apart and rebuild them, check responses."""

from __future__ import annotations

import re
from typing import List, Tuple

from ..netio import host_header

TLS_HANDSHAKE, TLS_ALERT = b"\x16", b"\x15"  # first byte of a TLS record
HOP_BY_HOP = {b"proxy-connection", b"connection", b"keep-alive", b"proxy-authorization", b"te", b"upgrade"}
PROXY_AUTH_REQUIRED = re.compile(rb"HTTP/1\.[01] 407\b")
STATUS_LEN = len(b"HTTP/1.1 407 ")
STATUS_RE = re.compile(rb"HTTP/1\.[01] (\d{3})[ \r\n]")  # exactly three digits – "4070" is not a 407
SCREEN_LIMIT = 16384            # bytes of one interim response
MAX_INTERIM = 8                 # interim responses (100 Continue, 103 Early Hints, ...) before the final one
MAX_INTERIM_BYTES = 64 * 1024   # all interim responses of one request together
# methods that may go to a second proxy after the first one could already have passed them on. Only the safe
# methods of RFC 9110 9.2.1: PUT and DELETE are idempotent by definition, but whether a target really behaves
# that way is its promise, not ours, and a proxy must not retry on its behalf (RFC 9110 9.2.2) – one lost
# response would otherwise run a payment, an upload or a delete twice. An Idempotency-Key header is no
# guarantee either: nothing tells us the target deduplicates on it.
SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"})


def parse_request_head(head: bytes) -> Tuple[str, str, int, bytes, List[Tuple[bytes, bytes]]]:
    """-> (method, host, port, path, headers). Supports CONNECT host:port and absolute URLs."""
    lines = head.split(b"\r\n")
    method, target, _version = lines[0].split(b" ", 2)
    headers = []
    for line in lines[1:]:
        if line:
            name, _, value = line.partition(b":")
            headers.append((name.strip(), value.strip()))
    if method == b"CONNECT":
        host, _, port = target.decode("ascii").rpartition(":")
        return "CONNECT", host.strip("[]"), _valid_port(port), b"", headers
    if not target.lower().startswith(b"http://"):
        raise ValueError("only absolute http:// URLs or CONNECT")
    rest = target[7:]
    hostport, slash, path = rest.partition(b"/")
    authority = hostport.decode("ascii")
    if authority.startswith("["):  # IPv6 literal: http://[2606:4700::1]:8080/
        host, _, after = authority[1:].partition("]")
        port = after[1:] if after.startswith(":") else ""
    else:
        host, _, port = authority.partition(":")
    return method.decode("ascii"), host, _valid_port(port or "80"), b"/" + path if slash else b"/", headers


_NOT_IN_HOSTNAME = re.compile(r"[\x00-\x20\x7f]")


def valid_hostname(host: str) -> bool:
    """Whether a target name can be sent to a proxy at all: no spaces or control characters (they would end up in
    the CONNECT line), and as the IDNA name SOCKS5 carries labels of 1-63 characters, 255 bytes at most."""
    if not host or len(host) > 255 or _NOT_IN_HOSTNAME.search(host):
        return False
    try:
        return len(host.encode("idna")) <= 255
    except UnicodeError:
        return False


def _valid_port(text: str) -> int:
    port = int(text)
    if not 0 < port < 65536:
        raise ValueError(f"invalid port {port}")
    return port


def origin_request(method: str, path: bytes, host: str, port: int, headers: List[Tuple[bytes, bytes]]) -> bytes:
    """Request for the target server: path instead of an absolute URL, no proxy headers, one request per connection."""
    lines = [f"{method} ".encode() + path + b" HTTP/1.1"]
    if not any(name.lower() == b"host" for name, _ in headers):
        lines.append(b"Host: " + host_header(host, port, False).encode())
    lines += [name + b": " + value for name, value in headers if name.lower() not in HOP_BY_HOP]
    lines.append(b"Connection: close")
    return b"\r\n".join(lines) + b"\r\n\r\n"


def forward_request(method: str, path: bytes, host: str, port: int, headers: List[Tuple[bytes, bytes]]) -> bytes:
    """Request to an HTTP upstream proxy: absolute URL as sent by the client, just without proxy headers."""
    authority = host_header(host, port, False)
    request = origin_request(method, path, host, port, headers)
    rest = request.split(b"\r\n", 1)[1]  # the first line is replaced by the absolute URL
    return f"{method} http://{authority}".encode() + path + b" HTTP/1.1\r\n" + rest


class ChunkedEnd:
    """Finds where a chunked request body ends, fed piece by piece. feed() returns how many bytes of this
    piece still belong to the body once the end is in it, otherwise None. Garbage raises ValueError."""

    MAX_LINE = 4096

    def __init__(self):
        self.line = b""
        self.left = 0  # bytes of chunk data (plus its CRLF) still to come
        self.trailer = False

    def feed(self, data: bytes):
        i = 0
        while i < len(data):
            if self.left:
                take = min(self.left, len(data) - i)
                self.left -= take
                i += take
                continue
            j = data.find(b"\n", i)
            if j < 0:
                self.line += data[i:]
                if len(self.line) > self.MAX_LINE:
                    raise ValueError("chunk line too long")
                return None
            line = (self.line + data[i:j]).rstrip(b"\r")
            self.line = b""
            i = j + 1
            if self.trailer:
                if not line:
                    return i
                continue
            size = int(line.split(b";", 1)[0].strip(), 16)
            if size < 0:
                raise ValueError("negative chunk size")
            if size:
                self.left = size + 2
            else:
                self.trailer = True
        return None


def request_body_length(headers: List[Tuple[bytes, bytes]]):
    """How much body follows the head: a byte count, or a ChunkedEnd for chunked bodies."""
    values = {name.lower(): value for name, value in headers}
    if b"chunked" in values.get(b"transfer-encoding", b"").lower():
        return ChunkedEnd()
    length = values.get(b"content-length", b"0").strip()
    return int(length) if length.isdigit() else 0


class ResponseScreen:
    """Checks the start of an upstream response until the final status line is there.

    Interim responses (100 Continue and the like) go to the client right away; if a 407 follows,
    the client should never see it. feed() returns what may already go on, and the decision:
    None = still open, "ok" = just pass everything else through, "407" = the proxy wants a login
    (or sends implausibly long or many interim responses – both mean: don't use this upstream)."""

    def __init__(self):
        self.buf = b""
        self.interim = 0        # interim responses seen so far
        self.interim_bytes = 0

    def feed(self, data: bytes):
        self.buf += data
        out = b""
        while True:
            head = self.buf
            if len(head) < STATUS_LEN and b"\n" not in head and head[:5] == b"HTTP/"[:len(head[:5])]:
                return out, None  # status line still incomplete
            m = STATUS_RE.match(head)
            if not m:
                return out + self._flush(), "ok"  # not an HTTP response (e.g. a tunnel) – nothing to check
            code = m.group(1)
            if code == b"407":
                return out, "407"
            if not code.startswith(b"1") or code == b"101":  # 101 Switching Protocols is final
                return out + self._flush(), "ok"
            end = head.find(b"\r\n\r\n")
            if end < 0:
                if len(head) > SCREEN_LIMIT:
                    return out, "407"  # huge interim response – better count it as failed than let it through blindly
                return out, None  # interim response not complete yet
            self.interim += 1
            self.interim_bytes += end + 4
            if self.interim > MAX_INTERIM or self.interim_bytes > MAX_INTERIM_BYTES:
                return out, "407"  # an endless stream of interim responses is no answer either
            out += head[:end + 4]
            self.buf = head[end + 4:]
            if not self.buf:
                return out, None

    def _flush(self) -> bytes:
        data, self.buf = self.buf, b""
        return data


def replay_safe_first_packet(data: bytes) -> bool:
    """May the client's first packet in a tunnel go to another proxy after the first one perhaps passed it on?

    Yes for nothing at all (the server talks first), for TLS handshake records only (a ClientHello carries no
    application data – but 0-RTT early data in the same packet would, so every record has to be a handshake)
    and for exactly one request head with a safe method (plain HTTP through CONNECT). Anything else could be
    a POST or a command of some other protocol: it is sent once."""
    if not data:
        return True
    if data[:1] == TLS_HANDSHAKE:
        i = 0
        while i < len(data):
            if data[i:i + 1] != TLS_HANDSHAKE:
                return False
            if len(data) - i < 5:
                return True
            i += 5 + int.from_bytes(data[i + 3:i + 5], "big")
        return True
    method, _, rest = data.partition(b" ")
    end = data.find(b"\r\n\r\n")
    return (method.decode("ascii", "replace") in SAFE_METHODS and b" HTTP/1." in rest.split(b"\r\n", 1)[0]
            and end == len(data) - 4)


def plausible_answer(first_out: bytes, first_in: bytes) -> bool:
    """Does the first response fit the request? If the client starts with a TLS handshake (0x16), the
    other side has to speak TLS too – some proxies send an HTTP error page inside the tunnel instead.
    A 407 always comes from the proxy itself (login missing or wrong), never from the target site."""
    if first_out[:1] == TLS_HANDSHAKE:
        return first_in[:1] in (TLS_HANDSHAKE, TLS_ALERT)
    return not PROXY_AUTH_REQUIRED.match(first_in)
