"""Offline URL selection fixture. This module never opens a URL or a socket."""
import argparse
import json
import re
from pathlib import Path
from urllib.parse import urldefrag, urljoin, urlsplit, urlunsplit

ROOT = Path(__file__).resolve().parent
BASE = "https://trusted.example/api/jobs/"
TRUSTED_ORIGIN = ("https", "trusted.example", 443)


class InvalidReference(ValueError):
    pass


def resolve_same_origin(reference):
    """Select a URL under a narrow, fixed HTTPS origin policy; perform no I/O.

    Input must already be ASCII URI text. The path is NOT an authorization
    boundary. Redirects, DNS, proxies and transport clients need separate policy.
    """
    if not isinstance(reference, str):
        raise InvalidReference("reference must be text")
    if len(reference) > 2048:
        raise InvalidReference("reference exceeds local policy length")
    if any(ord(ch) < 33 or ord(ch) > 126 or ch == "\\" for ch in reference):
        raise InvalidReference("raw whitespace, controls, backslash or non-ASCII")
    if re.search(r"%(?![0-9A-Fa-f]{2})", reference):
        raise InvalidReference("malformed percent escape")
    try:
        target = urlsplit(urljoin(BASE, reference))
        # Read .port explicitly: urlsplit alone does not validate its range.
        port = target.port
        effective_port = 443 if port is None else port
        if target.username is not None or target.password is not None:
            raise InvalidReference("userinfo is not allowed")
        if target.netloc.endswith(":"):
            raise InvalidReference("empty explicit port is not allowed")
        if (target.scheme, target.hostname, effective_port) != TRUSTED_ORIGIN:
            raise InvalidReference("resolved origin is not allowed")
        # Use the validated authority. Retain encoded path and query verbatim;
        # do not unquote, re-join or interpret them as another URL afterwards.
        return urlunsplit(("https", "trusted.example", target.path, target.query, ""))
    except (ValueError, UnicodeError) as exc:
        if isinstance(exc, InvalidReference):
            raise
        raise InvalidReference("URL parser rejected the reference") from exc


def evaluate(mode, reference):
    try:
        if mode == "fixed":
            selected = resolve_same_origin(reference)
        else:
            selected = urldefrag(urljoin(BASE, reference)).url
            if mode == "prefix" and not selected.startswith("https://trusted.example"):
                raise InvalidReference("naive prefix policy rejected")
        return {"accepted": True, "selected_url": selected}
    except (ValueError, TypeError, UnicodeError) as exc:
        return {"accepted": False, "error_type": type(exc).__name__}


def run(mode):
    fixture = json.loads((ROOT / "fixture.json").read_text(encoding="utf-8"))
    if fixture["base"] != BASE:
        raise ValueError("fixture and configured base differ")
    observations = []
    checks = []
    failed = []
    for case in fixture["cases"]:
        observed = evaluate(mode, case["reference"])
        passed = observed["accepted"] == case["accept"]
        if passed and case["accept"]:
            passed = observed["selected_url"] == case["selected_url"]
        (checks if passed else failed).append(case["id"])
        observations.append({"id": case["id"], "expected_accept": case["accept"], **observed})
    return {"mode": mode, "status": "passed" if not failed else "check_failed",
            "checks_count": len(checks), "checks": checks, "failed_checks": failed,
            "network_requests": 0, "observations": observations}


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("mode", choices=("broken", "prefix", "fixed"))
    result = run(parser.parse_args().mode)
    print(json.dumps(result, ensure_ascii=True, sort_keys=True))
    raise SystemExit(0 if result["status"] == "passed" else 2)
