#!/usr/bin/env python3
"""Measure public HTTPS CDN answers on this device. Nothing is uploaded."""

import argparse
import hashlib
import http.client
import ipaddress
import json
import re
import socket
import ssl
import statistics
import sys
import time
import urllib.request
from urllib.parse import urlencode, urlsplit

DEFAULT_HOST = "cdn.fastly.steamstatic.com"
DEFAULT_PATH = "/client/installer/SteamSetup.exe"
MAX_BYTES = 3_000_000
ROUND_COUNT = 3
TIMEOUT_SECONDS = 30
MAX_ADDRESSES = 8
RESOLVERS = {
    "Cloudflare": "https://cloudflare-dns.com/dns-query",
    "Google": "https://dns.google/resolve",
}


def parse_target(value):
    if not value:
        return DEFAULT_HOST, DEFAULT_PATH
    parsed = urlsplit(value)
    if (
        parsed.scheme != "https"
        or not parsed.hostname
        or parsed.port not in (None, 443)
        or parsed.username
        or parsed.password
        or parsed.query
        or parsed.fragment
    ):
        raise ValueError(
            "URL must be public HTTPS on port 443 with no credentials, query, or fragment"
        )
    if "." not in parsed.hostname or any(
        ord(c) < 33 or ord(c) == 127 for c in parsed.hostname
    ):
        raise ValueError("URL hostname must be a normal public DNS name")
    try:
        ipaddress.ip_address(parsed.hostname)
    except ValueError:
        return parsed.hostname.rstrip("."), parsed.path or "/"
    raise ValueError("URL hostname must be a public DNS name, not an IP address")


def is_public_ipv4(value):
    address = ipaddress.ip_address(value)
    return (
        address.version == 4
        and address.is_global
        and not address.is_multicast
        and not address.is_unspecified
    )


class PinnedHTTPSConnection(http.client.HTTPSConnection):
    def __init__(self, hostname, answer_ip, **kwargs):
        super().__init__(hostname, **kwargs)
        self.answer_ip = answer_ip

    def connect(self):
        raw = socket.create_connection((self.answer_ip, self.port), self.timeout)
        self.sock = self._context.wrap_socket(raw, server_hostname=self.host)


def doh_answers(hostname, endpoint):
    request = urllib.request.Request(
        endpoint
        + "?"
        + urlencode({"name": hostname, "type": "A", "cd": "0", "do": "0"}),
        headers={"Accept": "application/dns-json"},
    )
    started = time.monotonic()
    with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
        payload = json.load(response)
    elapsed = (time.monotonic() - started) * 1000
    if payload.get("Status") != 0:
        raise RuntimeError("DNS status %s" % payload.get("Status"))
    answers = [
        item["data"]
        for item in payload.get("Answer", [])
        if item.get("type") == 1
        and isinstance(item.get("data"), str)
        and is_public_ipv4(item["data"])
    ]
    if not answers:
        raise RuntimeError("no public IPv4 answer")
    return sorted(set(answers))[:MAX_ADDRESSES], elapsed


def _remaining(deadline):
    remaining = deadline - time.monotonic()
    if remaining <= 0:
        raise TimeoutError("transfer deadline exceeded")
    return remaining


def _expected_length(response):
    raw = response.getheader("Content-Length")
    if raw is None or not raw.isdigit():
        raise RuntimeError("missing or invalid Content-Length")
    length = int(raw)
    if response.status == 200:
        if length <= 0 or length > MAX_BYTES:
            raise RuntimeError("sample size %d is outside safe limit" % length)
        return length
    match = re.fullmatch(
        r"bytes 0-(\d+)/(\d+)", response.getheader("Content-Range") or ""
    )
    if not match:
        raise RuntimeError("invalid Content-Range")
    end, total = map(int, match.groups())
    expected = min(total, MAX_BYTES)
    if total <= 0 or end + 1 != expected or length != expected:
        raise RuntimeError("Content-Range does not match bounded sample")
    return expected


def download(hostname, path, answer_ip):
    """Fetch one exact body. ttfb_ms is time to first body byte, not response headers."""
    connection = PinnedHTTPSConnection(
        hostname,
        answer_ip,
        port=443,
        timeout=TIMEOUT_SECONDS,
        context=ssl.create_default_context(),
    )
    started = time.monotonic()
    deadline = started + TIMEOUT_SECONDS
    try:
        connection.request(
            "GET",
            path,
            headers={
                "Host": hostname,
                "Accept-Encoding": "identity",
                "Range": "bytes=0-%d" % (MAX_BYTES - 1),
                "Connection": "close",
            },
        )
        active_socket = connection.sock
        if active_socket:
            active_socket.settimeout(_remaining(deadline))
        response = connection.getresponse()
        if response.status not in (200, 206):
            raise RuntimeError("HTTP %s" % response.status)
        encoding = response.getheader("Content-Encoding")
        if isinstance(encoding, str) and encoding:
            raise RuntimeError("encoded response cannot be byte-compared")
        expected = _expected_length(response)
        if expected < 65_536:
            raise RuntimeError("sample smaller than 64 KiB")
        if response.headers.get_content_type() in ("text/html", "application/xhtml+xml"):
            raise RuntimeError("received a web page instead of a download")
        _remaining(deadline)
        if active_socket:
            active_socket.settimeout(_remaining(deadline))
        first = response.read(1)
        first_body = time.monotonic()
        if not first:
            raise RuntimeError("empty response body")
        digest = hashlib.sha256(first)
        count = 1
        while count < expected:
            _remaining(deadline)
            if active_socket:
                active_socket.settimeout(_remaining(deadline))
            block = response.read1(min(65536, expected - count))
            if not block:
                break
            count += len(block)
            digest.update(block)
        _remaining(deadline)
        completed = time.monotonic()
        if count != expected:
            raise RuntimeError("incomplete body %d/%d" % (count, expected))
        body_seconds = completed - first_body
        if body_seconds <= 0:
            raise RuntimeError("invalid body duration")
        return {
            "ip": answer_ip,
            "bytes": count,
            "sha256": digest.hexdigest(),
            "ttfb_ms": (first_body - started) * 1000,
            "body_seconds": body_seconds,
            "mbps": (count - 1) / body_seconds / 1_000_000,
        }
    finally:
        connection.close()


def summarize_runs(runs, sources):
    excluded = []
    complete = {}
    for ip, samples in runs.items():
        if len(samples) != ROUND_COUNT:
            excluded.append(
                (
                    ip,
                    sources[ip],
                    "requires %d complete samples; got %d"
                    % (ROUND_COUNT, len(samples)),
                )
            )
        else:
            complete[ip] = samples
    identities = {
        (s["bytes"], s["sha256"]) for samples in complete.values() for s in samples
    }
    if len(identities) > 1:
        return [], excluded + [
            (
                ip,
                sources[ip],
                "completed samples have different bodies; no arbitrary baseline selected",
            )
            for ip in complete
        ]
    valid = []
    for ip, samples in complete.items():
        valid.append(
            {
                "ip": ip,
                "sources": sources[ip],
                "bytes": samples[0]["bytes"],
                "sha256": samples[0]["sha256"],
                "ttfb_ms": statistics.median(s["ttfb_ms"] for s in samples),
                "mbps": statistics.median(s["mbps"] for s in samples),
                "samples": [
                    {"ttfb_ms": round(s["ttfb_ms"], 2), "mbps": round(s["mbps"], 4)}
                    for s in samples
                ],
            }
        )
    return sorted(valid, key=lambda item: item["mbps"], reverse=True), excluded


def write_report(filename, hostname, resolvers, nodes, digest, sample_bytes):
    if not filename:
        return
    with open(filename, "x", encoding="utf-8") as output:
        json.dump(
            {
                "schema": "dnsviewer-download-test/v1",
                "target": {"host": hostname},
                "resolvers": resolvers,
                "nodes": nodes,
                "eligible_digest": digest,
                "eligible_bytes": sample_bytes,
            },
            output,
            ensure_ascii=False,
            indent=2,
        )
        output.write("\n")
    print("Local report written: %s" % filename)


def main():
    parser = argparse.ArgumentParser(
        description="Measure a bounded public HTTPS sample through DNS-selected CDN IPs."
    )
    parser.add_argument("--url")
    parser.add_argument("--report", metavar="FILE.json")
    arguments = parser.parse_args()
    try:
        hostname, path = parse_target(arguments.url)
    except ValueError as error:
        parser.error(str(error))
    print("DNSViewer local CDN sample\nTarget host: %s (path withheld)" % hostname)
    sources = {}
    resolver_rows = []
    for label, endpoint in RESOLVERS.items():
        try:
            answers, elapsed = doh_answers(hostname, endpoint)
            resolver_rows.append(
                {"label": label, "dns_ms": round(elapsed, 2), "answers": answers}
            )
            for ip in answers:
                sources.setdefault(ip, []).append(label)
            print("%s DNS: %.0f ms -> %s" % (label, elapsed, ", ".join(answers)))
        except Exception as error:
            resolver_rows.append(
                {"label": label, "dns_ms": None, "answers": [], "reason": str(error)}
            )
            print("%s DNS excluded: %s" % (label, error))
    if not sources:
        write_report(arguments.report, hostname, resolver_rows, [], None, None)
        return 2
    runs = {ip: [] for ip in sources}
    excluded = []
    addresses = sorted(sources)
    for round_number in range(ROUND_COUNT):
        ordered = addresses if round_number % 2 == 0 else list(reversed(addresses))
        for ip in ordered:
            print(
                "Sample %d/%d from %s (%s)..."
                % (round_number + 1, ROUND_COUNT, ip, "+".join(sources[ip]))
            )
            try:
                runs[ip].append(download(hostname, path, ip))
            except Exception as error:
                excluded.append(
                    (ip, sources[ip], "sample %d: %s" % (round_number + 1, error))
                )
    valid, invalid = summarize_runs(runs, sources)
    excluded.extend(invalid)
    print(
        "\nEligible nodes — median of %d complete identical-body samples" % ROUND_COUNT
    )
    for rank, item in enumerate(valid, 1):
        print(
            "%d. %s | %s | first body byte %.0f ms | median %.2f MB/s"
            % (
                rank,
                item["ip"],
                "+".join(item["sources"]),
                item["ttfb_ms"],
                item["mbps"],
            )
        )
    if valid and len({tuple(item["sources"]) for item in valid}) == 1:
        print("No DNS winner: all eligible IPs came from the same DNS source set.")
    excluded_by_ip = {}
    for ip, labels, reason in excluded:
        excluded_by_ip.setdefault(
            ip, {"ip": ip, "sources": labels, "status": "excluded", "reason": reason}
        )
    for node in excluded_by_ip.values():
        print("Unranked %s: %s" % (node["ip"], node["reason"]))
    nodes = [
        {
            "ip": item["ip"],
            "sources": item["sources"],
            "status": "eligible",
            "bytes": item["bytes"],
            "sha256": item["sha256"],
            "ttfb_ms": round(item["ttfb_ms"], 2),
            "mbps": round(item["mbps"], 4),
            "samples": item["samples"],
        }
        for item in valid
    ] + list(excluded_by_ip.values())
    write_report(
        arguments.report,
        hostname,
        resolver_rows,
        nodes,
        valid[0]["sha256"] if valid else None,
        valid[0]["bytes"] if valid else None,
    )
    return 0 if valid else 1


if __name__ == "__main__":
    sys.exit(main())
