#!/usr/bin/env python3
"""Fixed loopback experiments, not a production HTTP server or downloader."""

import hashlib
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import threading
from urllib.error import HTTPError
from urllib.request import build_opener, ProxyHandler, Request


FIXTURES = {
    "a": b"version-A|0123456789|abcdefghijklmnopqrstuvwxyz\n",
    "b": b"version-B|9876543210|zyxwvutsrqponmlkjihgfedcba\n",
    "empty": b"",
    "utf8": "谷米\n".encode("utf-8"),
}


def sha(data):
    return hashlib.sha256(data).hexdigest()


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):
        pass

    def do_GET(self):
        if self.path != "/asset":
            self.send_error(404)
            return
        payload = FIXTURES[self.server.fixture]
        etag = f'"rev-{self.server.fixture}"'
        range_value = self.headers.get("Range")
        if_range = self.headers.get("If-Range")
        status, body, content_range = 200, payload, None
        # This teaching subset supports one byte range and strong ETags only.
        # Unsupported/malformed syntax is deliberately ignored (full 200).
        match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_value or "")
        apply_range = (self.server.honor_ranges and match
                       and (if_range is None or if_range == etag))
        if apply_range:
            first, last = match.groups()
            n = len(payload)
            if first and (not last or int(last) >= int(first)):
                start, end = int(first), min(int(last) if last else n - 1, n - 1)
            elif not first and last:
                count = int(last)
                start, end = max(0, n - count), n - 1
                if count == 0:
                    start = n
            else:
                start, end = None, None
            if start is not None:
                if n == 0 or start >= n:
                    status, body, content_range = 416, b"", f"bytes */{n}"
                else:
                    status, body = 206, payload[start:end + 1]
                    content_range = f"bytes {start}-{end}/{n}"

        self.send_response(status)
        self.send_header("Content-Type", "application/octet-stream")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("ETag", etag)
        self.send_header("Accept-Ranges", "bytes" if self.server.honor_ranges else "none")
        if content_range:
            self.send_header("Content-Range", content_range)
        self.end_headers()
        self.server.trace.append({"fixture": self.server.fixture,
                                  "request_range": range_value, "request_if_range": if_range,
                                  "accept_encoding": self.headers.get("Accept-Encoding"),
                                  "status": status, "etag": etag,
                                  "content_range": content_range, "body_length": len(body)})
        try:
            self.wfile.write(body)
        except BrokenPipeError:
            # curl may close after rejecting a non-resumable 200 response.
            pass


def main():
    curl = shutil.which("curl")
    if curl is None:
        raise RuntimeError("curl is required for the two independent client checks")
    curl_version = subprocess.check_output([curl, "-q", "--version"], text=True).splitlines()[0]
    server = HTTPServer(("127.0.0.1", 0), Handler)
    server.fixture, server.honor_ranges, server.trace = "a", True, []
    worker = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)
    worker.start()
    url = f"http://127.0.0.1:{server.server_port}/asset"
    opener = build_opener(ProxyHandler({}))
    cases = []

    def get(name, range_value=None, if_range=None):
        headers = {"Accept-Encoding": "identity"}
        if range_value is not None:
            headers["Range"] = range_value
        if if_range is not None:
            headers["If-Range"] = if_range
        try:
            response = opener.open(Request(url, headers=headers), timeout=5)
        except HTTPError as exc:
            response = exc
        with response:
            body = response.read()
            row = {"name": name, "request_headers": headers, "status": response.code,
                   "response_headers": {key: response.headers[key] for key in
                                        ("Content-Length", "ETag", "Accept-Ranges", "Content-Range")
                                        if key in response.headers},
                   "body_length": len(body), "body_hex": body.hex(), "sha256": sha(body)}
        cases.append(row)
        return row, body

    try:
        a, b = FIXTURES["a"], FIXTURES["b"]
        assert len(a) == len(b) == 48
        full, body = get("full_a")
        assert full["status"] == 200 and body == a
        first, prefix = get("first_ten_a", "bytes=0-9")
        assert first["status"] == 206 and prefix == a[:10]
        assert first["response_headers"]["Content-Range"] == "bytes 0-9/48"
        same, tail = get("resume_same_a", "bytes=10-", '"rev-a"')
        assert same["status"] == 206
        assert same["response_headers"]["Content-Range"] == "bytes 10-47/48"
        assert same["response_headers"]["ETag"] == '"rev-a"'
        assert len(tail) == 38 and prefix + tail == a

        server.fixture = "b"
        bare, new_tail = get("changed_without_if_range", "bytes=10-")
        hybrid = prefix + new_tail
        assert bare["status"] == 206 and len(hybrid) == 48
        assert hybrid != a and hybrid != b
        guarded, new_full = get("changed_with_if_range", "bytes=10-", '"rev-a"')
        assert guarded["status"] == 200 and new_full == b
        wrong_append = prefix + new_full
        assert len(wrong_append) == 58 and wrong_append != b

        server.honor_ranges = False
        ignored, ignored_body = get("server_ignores_range", "bytes=10-", '"rev-b"')
        assert ignored["status"] == 200 and ignored_body == b
        server.honor_ranges = True
        suffix, suffix_body = get("last_five_bytes", "bytes=-5")
        assert suffix["status"] == 206 and suffix_body == b[-5:]
        clamped, clamped_body = get("end_beyond_length", "bytes=44-999")
        assert clamped["status"] == 206 and clamped_body == b[44:]
        assert clamped["response_headers"]["Content-Range"] == "bytes 44-47/48"
        outside, outside_body = get("start_equals_length", f"bytes={len(hybrid)}-")
        assert outside["status"] == 416 and outside_body == b""
        assert outside["response_headers"]["Content-Range"] == "bytes */48"
        server.fixture = "empty"
        empty, empty_body = get("empty_representation", "bytes=0-")
        assert empty["status"] == 416 and empty_body == b""
        assert empty["response_headers"]["Content-Range"] == "bytes */0"
        server.fixture = "utf8"
        unicode_row, one_byte = get("one_byte_of_utf8", "bytes=0-0")
        assert unicode_row["status"] == 206 and one_byte == b"\xe8"
        try:
            one_byte.decode("utf-8")
        except UnicodeDecodeError:
            utf8_split_rejected = True
        else:
            raise AssertionError("a partial UTF-8 character unexpectedly decoded")

        curl_cases = []
        with tempfile.TemporaryDirectory(prefix="gumi-http-resume-") as tmp:
            for fixture, filename in (("a", "same.part"), ("b", "changed.part")):
                server.fixture = fixture
                output = Path(tmp) / filename
                output.write_bytes(prefix)
                args = [curl, "-q", "--silent", "--show-error", "--max-time", "10",
                        "--noproxy", "*", "--header", "Accept-Encoding: identity",
                        "--continue-at", "-", "--header", 'If-Range: "rev-a"',
                        "--output", filename, url]
                result = subprocess.run(args, cwd=tmp, text=True, capture_output=True)
                actual = output.read_bytes()
                curl_cases.append({"fixture": fixture,
                                   "command_with_dynamic_URL_redacted": ["curl"] + args[1:-1] + ["<loopback-url>"],
                                   "exit_code": result.returncode, "stderr": result.stderr.strip(),
                                   "output_length": len(actual), "output_sha256": sha(actual),
                                   "equals_a": actual == a, "equals_old_prefix": actual == prefix})
                if fixture == "a":
                    assert result.returncode == 0 and actual == a
                else:
                    assert result.returncode != 0 and actual == prefix
        assert len(cases) == 11 and len(server.trace) == 13
        assert all(row["accept_encoding"] == "identity" for row in server.trace)
        report = {"date": "2026-10-28", "environment": {"python": platform.python_version(),
                    "macos": platform.mac_ver()[0], "machine": platform.machine(), "curl": curl_version},
                  "kind": "actual sequential loopback HTTP exchanges with a hand-written teaching handler",
                  "fixtures": {key: {"bytes": len(value), "body_hex": value.hex(), "sha256": sha(value),
                                     "etag": f'"rev-{key}"'} for key, value in FIXTURES.items()},
                  "python_requests": cases, "server_trace": server.trace,
                  "assembly": {"same_version_sha256": sha(prefix + tail),
                               "hybrid_length": len(hybrid), "hybrid_sha256": sha(hybrid),
                               "hybrid_equals_a": hybrid == a, "hybrid_equals_b": hybrid == b,
                               "naive_append_200_length": len(wrong_append),
                               "replace_with_200_equals_b": new_full == b},
                  "utf8_split_rejected": utf8_split_rejected, "curl_cases": curl_cases,
                  "limits": ["HTTP/1.0 over loopback; one byte range, fixed identity-coded fixtures.",
                             "No TLS, CDN/proxy, browser, redirects, gzip, multipart ranges or HTTP-date validators tested.",
                             "No real interrupted transport, disk crash/recovery, concurrency or throughput test.",
                             "Partial prefixes are deliberately prepared; all range requests and curl resumes are real.",
                             "Not the built-in SimpleHTTPRequestHandler's default range behavior."]}
    finally:
        server.shutdown()
        server.server_close()
        worker.join(timeout=2)
        assert not worker.is_alive()
    report["server_closed"] = True
    json.dump(report, sys.stdout, ensure_ascii=False, indent=2)
    print()


if __name__ == "__main__":
    main()
