#!/usr/bin/env python3
"""Read-only HTTP conformance runner for the Media Discussions alpha pilot."""

import argparse
from collections import Counter
import hashlib
from html.parser import HTMLParser
import http.client
import json
import re
from urllib.parse import urlencode, urljoin, urlsplit

NSID = "com.danhon.atprotomedia."
MAX_BODY = 4 * 1024 * 1024
SEMVER = re.compile(
    r"(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)"
    r"(?:-(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*)"
    r"(?:\.(?:0|[1-9][0-9]*|[0-9A-Za-z-]*[A-Za-z-][0-9A-Za-z-]*))*)?"
    r"(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?"
)
DID = re.compile(r"did:(?:plc:[a-z2-7]{24}|web:[a-z0-9-]+(?:\.[a-z0-9-]+)+)")
BBC = "https://www.bbc.co.uk/iplayer/episode/m001zpzs/doctor-who-season-1-4-73-yards"
IMDB = "https://www.imdb.com/title/tt28704625/"
FANFARE = "https://fanfare.metafilter.com/24173/Doctor-Who-73-Yards"
REDDIT = "https://www.reddit.com/r/doctorwho/comments/1czz9u3/doctor_who_1x04_73_yards_postepisode_discussion/"
APPLE_SHOW = "umc.cmc.1zzly0vah46bnvnwf0qkrjhh2"
APPLE_EPISODES = (
    ("Welcome to Widow’s Bay!", "welcome-to-widows-bay", "66qky4nskhbw2mdz0dt3oc0gu", "2026-04-29"),
    ("Lodging", "lodging", "4r38lqta57d7elcn17jadr9q2", "2026-04-29"),
    ("The Inaugural Swim", "the-inaugural-swim", "3hc8pqdxv425z28dimn20okjt", "2026-05-06"),
    ("Beach Reads", "beach-reads", "33zziday39uosnuudyanogle9", "2026-05-13"),
    ("What to Expect on Your Trip", "what-to-expect-on-your-trip", "50a7x3k38hqzxi6h5ucx227z8", "2026-05-20"),
    ("Our History", "our-history", "2po66zn56kkldifsqlibssv6h", "2026-05-27"),
    ("Seasickness", "seasickness", "78ny2d98bpcyoos8rwte9yits", "2026-05-27"),
    ("Your Baggage", "your-baggage", "1hqqihwv5pry1xpvkvpr89twr", "2026-06-03"),
    ("Emergency Shelter", "emergency-shelter", "1obp09hh8ujq92x8nen6u0pj7", "2026-06-10"),
    ("We Hope You Enjoyed Your Time!", "we-hope-you-enjoyed-your-time", "590b26bcb5cnm7wh2lhtd65hl", "2026-06-17"),
)
EPISODES = (
    ("73-yards", "doctor-who-2024-73-yards", "doctor-who-2024", "73 Yards", 4, "2024-05-25",
     (("bbc", "m001zpzs", BBC), ("imdb", "tt28704625", IMDB))),
    *((f"widows-bay-s01e{number:02}", f"widows-bay-s01e{number:02}", "widows-bay",
       title, number, date,
       (("apple-tv", f"umc.cmc.{key}",
         f"https://tv.apple.com/us/episode/{slug}/umc.cmc.{key}?showId={APPLE_SHOW}"),))
      for number, (title, slug, key, date) in enumerate(APPLE_EPISODES, 1)),
)
TITLE = {"type": "string", "maxLength": 512}
DESCRIPTION = {"type": "string", "maxLength": 3000}
AT_URI = {"type": "string", "format": "at-uri"}
DATETIME = {"type": "string", "format": "datetime"}
NUMBER = {"type": "integer", "minimum": 0}
RECORDS = {
    "series": (("title",), {"title": TITLE, "description": DESCRIPTION}),
    "season": (("title", "seriesUri"), {"title": TITLE, "seriesUri": AT_URI, "number": NUMBER}),
    "episode": (("title", "seriesUri"), {
        "title": TITLE, "description": DESCRIPTION, "seriesUri": AT_URI, "seasonUri": AT_URI,
        "seasonNumber": NUMBER, "episodeNumber": NUMBER,
        "airDate": {"type": "string", "minLength": 10, "maxLength": 10},
    }),
    "mapping": (("source", "externalId", "url", "episodeUri"), {
        "source": {"type": "string", "maxLength": 100,
                   "knownValues": ["apple-tv", "bbc", "episode-page", "imdb"]},
        "externalId": {"type": "string", "maxLength": 512},
        "url": {"type": "string", "format": "uri", "maxLength": 2048}, "episodeUri": AT_URI,
    }),
    "reply": (("episode", "text", "createdAt"), {
        "episode": AT_URI, "text": {"type": "string", "maxLength": 4000, "maxGraphemes": 1000},
        "createdAt": DATETIME,
    }),
    "watch": (("episode", "watchedAt"), {"episode": AT_URI, "watchedAt": DATETIME}),
}
SCHEMAS = (*RECORDS, "watchspace")
DOC_AGENT = "/docs/agents.md"
DOC_INDEX = "/docs/lexicons"
MISSING = "conformance-fixture-missing"


class Failure(Exception):
    """A server response failed a named check."""


def require(condition, message):
    if not condition:
        raise Failure(message)


def object_value(value, label):
    require(isinstance(value, dict), f"{label} must be a JSON object")
    return value


def array_value(value, label):
    require(isinstance(value, list), f"{label} must be a JSON array")
    return value


def fields(value, expected, label):
    value = object_value(value, label)
    for key, expected_value in expected.items():
        require(key in value and type(value[key]) is type(expected_value) and value[key] == expected_value,
                f"{label}.{key} must equal {expected_value!r}")


def nonempty(value, label):
    require(isinstance(value, str) and bool(value.strip()), f"{label} must be a nonempty string")


class Page(HTMLParser):
    def __init__(self, text, origin):
        super().__init__(convert_charrefs=True)
        self.origin = origin
        self.links = set()
        self.canonical = []
        self.meta = {}
        self.feed(text)
        self.close()

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        href = attrs.get("href")
        if tag in ("a", "link") and href:
            self.links.add(urljoin(self.origin, href))
        if tag == "link" and "canonical" in (attrs.get("rel") or "").split():
            self.canonical.append(href)
        if tag == "meta":
            name = attrs.get("property") or attrs.get("name")
            if name:
                self.meta[name] = attrs.get("content")


class Suite:
    def __init__(self, origin, timeout, quiet):
        self.origin = origin
        self.target = urlsplit(origin)
        self.timeout = timeout
        self.quiet = quiet
        self.results = []
        self.version = None
        self.publisher = None

    def case(self, name, check, *args):
        try:
            value = check(*args)
        except (Failure, ValueError) as error:
            # Error messages can come from response parsers. Never include raw response bodies.
            message = str(error) if isinstance(error, Failure) else "invalid response data"
            result = {"name": name, "status": "fail", "message": message}
            value = None
        else:
            result = {"name": name, "status": "pass"}
        self.results.append(result)
        if not self.quiet:
            detail = f" — {result['message']}" if "message" in result else ""
            print(f"{result['status'].upper():4} {name}{detail}")
        return value

    def get(self, path, *, status=200, mime=None, public=False, head=False):
        method = "HEAD" if head else "GET"
        path_label = path if len(path) <= 160 else path.split("?", 1)[0] + "?..."
        label = f"{method} {path_label}"
        connection_class = http.client.HTTPSConnection if self.target.scheme == "https" else http.client.HTTPConnection
        connection = connection_class(self.target.hostname, self.target.port, timeout=self.timeout)
        try:
            connection.request(method, path, headers={
                "Origin": "https://conformance-client.example",
                "User-Agent": "Media-Discussions-Conformance/1",
                "Accept-Encoding": "identity",
            })
            response = connection.getresponse()
            require(response.status == status, f"{label}: expected HTTP {status}, got {response.status}")
            if mime:
                actual = response.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
                require(actual == mime, f"{label}: expected Content-Type {mime}")
            if public:
                require(response.headers.get("Access-Control-Allow-Origin") == "*",
                        f"{label}: expected Access-Control-Allow-Origin: *")
                require(response.headers.get("Set-Cookie") is None,
                        f"{label}: public response sets a cookie")
            body = response.read(MAX_BODY + 1)
            require(len(body) <= MAX_BODY, f"{label}: response exceeds {MAX_BODY} bytes")
            if head:
                require(not body, f"{label}: expected an empty body")
            return response.headers, body
        except (OSError, http.client.HTTPException) as error:
            raise Failure(f"{label}: transport failure ({type(error).__name__})") from error
        finally:
            connection.close()

    def json(self, path, *, status=200, public=True):
        _, body = self.get(path, status=status, mime="application/json", public=public)
        try:
            return object_value(json.loads(body), path)
        except (ValueError, RecursionError) as error:
            raise Failure(f"GET {path}: invalid JSON object") from error

    def text(self, path, mime):
        _, body = self.get(path, mime=mime, public=True)
        return body.decode("utf-8")

    def redirect(self, path, canonical, status):
        headers, _ = self.get(path, status=status)
        location = headers.get("Location")
        require(location and urljoin(self.origin, location) == self.origin + canonical,
                f"GET {path}: redirect must point to {canonical}")

    def health(self, expected_version):
        health = self.json("/api/healthz", public=False)
        fields(health, {"status": "ok"}, "health")
        version = health.get("version")
        require(isinstance(version, str) and SEMVER.fullmatch(version), "health.version must be SemVer")
        self.version = version
        if expected_version:
            require(version == expected_version, f"health.version must equal {expected_version!r}")

    def docs_discovery(self):
        html = self.text("/docs", "text/html")
        links = Page(html, self.origin).links
        for path in ("/llms.txt", DOC_INDEX, DOC_AGENT):
            require(self.origin + path in links, f"/docs must link to {path}")
        discovery = self.text("/llms.txt", "text/plain")
        for path in ("/docs", DOC_INDEX, DOC_AGENT):
            pattern = r"\]\((?:" + re.escape(self.origin) + r")?" + re.escape(path) + r"\)"
            require(re.search(pattern, discovery), f"/llms.txt must link to {path}")
        agent = self.text(DOC_AGENT, "text/markdown")
        require(self.version is not None, "health.version is required to verify discovery")
        for path, body in (("/docs", html), ("/llms.txt", discovery), (DOC_AGENT, agent)):
            require(self.version in body, f"{path} must state the same version as health")
        self.get(DOC_INDEX, mime="application/json", public=True, head=True)

    def schema_index(self):
        index = self.json(DOC_INDEX)
        require(self.version is not None, "health.version is required to verify the Lexicon index")
        fields(index, {"version": self.version}, "Lexicon index")
        entries = {}
        for entry in array_value(index.get("lexicons"), "Lexicon index.lexicons"):
            entry = object_value(entry, "Lexicon index entry")
            schema_id = entry.get("id")
            nonempty(schema_id, "Lexicon index entry.id")
            require(schema_id not in entries, "Lexicon index repeats an ID")
            href = entry.get("href")
            nonempty(href, "Lexicon index entry.href")
            entries[schema_id] = href
        for name in SCHEMAS:
            schema_id = NSID + name
            path = f"{DOC_INDEX}/{schema_id}.json"
            require(schema_id in entries and urljoin(self.origin, entries[schema_id]) == self.origin + path,
                    f"Lexicon index must link {schema_id} to {path}")

    def schema(self, name):
        schema_id = NSID + name
        schema = self.json(f"{DOC_INDEX}/{schema_id}.json")
        fields(schema, {"id": schema_id, "lexicon": 1}, name)
        defs = object_value(schema.get("defs"), f"{name}.defs")
        main = object_value(defs.get("main"), f"{name}.defs.main")
        if name == "watchspace":
            fields(main, {"type": "space", "key": "literal:self", "collections": [NSID + "watch"]},
                   "watch Space schema")
            return
        fields(main, {"type": "record", "key": "any"}, f"{name}.defs.main")
        required, properties = RECORDS[name]
        record = object_value(main.get("record"), f"{name}.record")
        fields(record, {"type": "object"}, f"{name}.record")
        actual_required = array_value(record.get("required"), f"{name}.record.required")
        require(all(isinstance(key, str) for key in actual_required) and sorted(actual_required) == sorted(required),
                f"{name}.record.required must contain {', '.join(required)}")
        actual_properties = object_value(record.get("properties"), f"{name}.record.properties")
        for key, expected in properties.items():
            fields(actual_properties.get(key), expected, f"{name}.{key}")

    def episode(self, fixture, catalog):
        episode_id, key, series_key, title, number, air_date, sources = fixture
        page = f"/episodes/{episode_id}"
        path = "/api" + page
        payload = self.json(path)
        episode = object_value(payload.get("episode"), f"{path}.episode")
        series = payload.get("series")
        season = payload.get("season")
        if catalog == "live" and episode_id == "73-yards":
            uri = episode.get("uri")
            require(isinstance(uri, str), "live catalog must expose an episode AT URI")
            parsed = urlsplit(uri)
            require(parsed.scheme == "at" and DID.fullmatch(parsed.netloc),
                    "catalog publisher must be a DID supported by the pilot")
            self.publisher = parsed.netloc
        require(catalog == "demo" or self.publisher is not None,
                "a publisher DID is required from /api/episodes/73-yards")
        season_key = f"{series_key}-season-1"
        uri = self.uri("episode", key)
        series_uri = self.uri("series", series_key)
        season_uri = self.uri("season", season_key)
        fields(episode, {
            "id": episode_id, "key": key, "title": title, "path": page, "url": self.origin + page, "uri": uri,
            "seriesUri": series_uri, "seasonUri": season_uri,
            "seasonNumber": 1, "episodeNumber": number, "airDate": air_date,
        }, f"{path}.episode")
        fields(series, {"key": series_key, "uri": series_uri}, f"{path}.series")
        fields(season, {"key": season_key, "number": 1, "uri": season_uri, "seriesUri": series_uri}, f"{path}.season")
        nonempty(series.get("title"), f"{path}.series.title")
        nonempty(season.get("title"), f"{path}.season.title")
        actual_sources = array_value(episode.get("sources"), f"{path}.episode.sources")
        for source, _, url in sources:
            require(any(isinstance(item, dict) and item.get("source") == source and item.get("url") == url
                        and isinstance(item.get("label"), str) and item["label"].strip() for item in actual_sources),
                    f"{path} must preserve the labeled {source} source URL {url}")
        if sources[0][0] == "apple-tv":
            fields(episode, {"watchUrl": sources[0][2]}, f"{path}.episode")
        mappings = array_value(payload.get("mappings"), f"{path}.mappings")
        for source, external_id, url in (*sources, ("episode-page", episode_id, self.origin + page)):
            matches = [mapping for mapping in mappings if isinstance(mapping, dict)
                       and mapping.get("source") == source and mapping.get("externalId") == external_id]
            require(len(matches) == 1, f"{path} must have one {source} mapping for {external_id}")
            fields(matches[0], {
                "url": url, "episodeId": episode_id, "episodeUri": uri, "publisherDid": self.publisher,
            }, f"{path}.{source} mapping")
        discussions = array_value(payload.get("discussions"), f"{path}.discussions")
        if episode_id == "73-yards":
            phases = set()
            urls = set()
            for discussion in discussions:
                discussion = object_value(discussion, "discussion")
                for key in ("title", "source", "phase", "spoilers", "url"):
                    nonempty(discussion.get(key), f"discussion.{key}")
                phases.add(discussion["phase"])
                urls.add(discussion["url"])
            require({"pre-episode", "release-night", "post-episode"} <= phases,
                    "73-yards must attribute discussions across the three spoiler phases")
            require({FANFARE, REDDIT} <= urls, "73-yards must preserve pilot FanFare and Reddit links")
        return payload

    def uri(self, kind, key):
        return f"at://{self.publisher}/{NSID}{kind}/{key}" if self.publisher else None

    def resolve(self, url, payload, source, external_id):
        query = urlencode({"url": url})
        result = self.json(f"/api/resolve?{query}")
        require(payload is not None, "episode API result is required to verify resolver agreement")
        episode = payload["episode"]
        known_mapping = next(mapping for mapping in payload["mappings"] if isinstance(mapping, dict)
                             and mapping.get("source") == source and mapping.get("externalId") == external_id)
        fields(result, {"episode": episode, "mapping": known_mapping}, f"{source} resolver result")

    def unresolved(self, url):
        query = "?" + urlencode({"url": url}) if url is not None else ""
        payload = self.json("/api/resolve" + query, status=404)
        fields(payload, {"status": "unresolved"}, "unresolved response")

    def ambiguous(self, url):
        payload = self.json("/api/resolve?" + urlencode({"url": url}), status=409)
        fields(payload, {"status": "ambiguous"}, "ambiguous response")
        require("episode" not in payload and "mapping" not in payload,
                "ambiguous response must leave the episode and mapping unassigned")

    def page(self, episode_id, watch_url=None):
        path = f"/episodes/{episode_id}"
        _, body = self.get(path, mime="text/html")
        page = Page(body.decode("utf-8"), self.origin)
        canonical = self.origin + path
        require(page.canonical == [canonical], f"{path}: expected one canonical link to {canonical}")
        fields(page.meta, {"og:url": canonical}, f"{path} Open Graph")
        for key in ("og:title", "og:type", "og:description", "og:image", "og:image:alt", "twitter:card"):
            nonempty(page.meta.get(key), f"{path} {key}")
        require(watch_url is None or watch_url in page.links, f"{path}: missing official Apple TV watch link")
        if episode_id == "73-yards":
            require({FANFARE, REDDIT} <= page.links, f"{path}: missing original discussion links")
        image = urlsplit(page.meta["og:image"])
        require(image.scheme in ("http", "https") and image.netloc and not image.username and not image.password,
                f"{path}: og:image must be a public absolute URL")
        if image.scheme + "://" + image.netloc == self.origin:
            image_path = image.path or "/"
            if image.query:
                image_path += "?" + image.query
            headers, body = self.get(image_path)
            require(headers.get("Content-Type", "").startswith("image/") and body,
                    f"{path}: same-origin og:image must return an image")

    def catalog(self, mode):
        if mode == "demo":
            response = self.json("/api/catalog", status=503)
            fields(response, {"status": "catalog-identity-unconfigured"}, "catalog response")
            return
        require(self.publisher is not None, "a publisher DID is required from /api/episodes/73-yards")
        manifest = self.json("/api/catalog")
        records = array_value(manifest.get("records"), "catalog.records")
        by_uri = {}
        for row in records:
            row = object_value(row, "catalog entry")
            collection, key = row.get("collection"), row.get("rkey")
            require(collection in tuple(NSID + kind for kind in ("series", "season", "episode", "mapping")),
                    "catalog contains a collection outside the pilot's public manifest")
            require(isinstance(key, str) and re.fullmatch(r"[a-zA-Z0-9._~:-]{1,512}", key) and key not in (".", ".."),
                    "catalog entry must have a valid AT Protocol record key")
            value = object_value(row.get("record"), "catalog entry.record")
            fields(value, {"$type": collection}, "catalog entry.record")
            uri = self.uri(collection[len(NSID):], key)
            require(uri not in by_uri, "catalog repeats a collection and record key")
            by_uri[uri] = value
        expected_count = {"series": 2, "season": 2, "episode": 11, "mapping": 23}
        actual_count = Counter(record["$type"][len(NSID):] for record in by_uri.values())
        require(actual_count == expected_count, "catalog must contain 2 series, 2 seasons, 11 episodes and 23 mappings")
        for episode_id, key, series_key, title, number, air_date, sources in EPISODES:
            episode = self.uri("episode", key)
            series = self.uri("series", series_key)
            season = self.uri("season", series_key + "-season-1")
            fields(by_uri.get(episode), {
                "title": title, "seriesUri": series, "seasonUri": season,
                "seasonNumber": 1, "episodeNumber": number, "airDate": air_date,
            }, f"catalog episode {key}")
            fields(by_uri.get(season), {"seriesUri": series, "number": 1}, f"catalog season {series_key}")
            for uri in (series, season):
                value = object_value(by_uri.get(uri), f"catalog {uri}")
                nonempty(value.get("title"), f"catalog {uri}.title")
            for source, external_id, url in (*sources, ("episode-page", episode_id, f"{self.origin}/episodes/{episode_id}")):
                identity = url if source == "episode-page" else external_id
                hash_prefix = hashlib.sha256(identity.encode("utf-8")).hexdigest()[:24]
                mapping = self.uri("mapping", f"{source}-{hash_prefix}")
                fields(by_uri.get(mapping), {
                    "source": source, "externalId": external_id, "url": url, "episodeUri": episode,
                }, f"catalog {source} mapping for {external_id}")

    def oauth_metadata(self):
        path = "/oauth-client-metadata.json"
        metadata = self.json(path, public=False)
        fields(metadata, {
            "client_id": self.origin + path, "jwks_uri": self.origin + "/.well-known/jwks.json",
            "token_endpoint_auth_method": "private_key_jwt", "token_endpoint_auth_signing_alg": "ES256",
            "dpop_bound_access_tokens": True,
        }, "OAuth client metadata")
        for key, expected in (("redirect_uris", self.origin + "/oauth/callback"),
                              ("grant_types", "authorization_code"), ("grant_types", "refresh_token"),
                              ("response_types", "code")):
            require(expected in array_value(metadata.get(key), f"OAuth client metadata.{key}"),
                    f"OAuth client metadata.{key} must contain {expected}")
        scope = metadata.get("scope")
        nonempty(scope, "OAuth client metadata.scope")
        require({"atproto", "repo:" + NSID + "reply"} <= set(scope.split()),
                "OAuth client metadata must advertise identity and reply collection scopes")
        jwks = self.json("/.well-known/jwks.json", public=False)
        keys = array_value(jwks.get("keys"), "JWKS.keys")
        require(keys, "JWKS must contain a public signing key")
        ids = set()
        private_fields = {"d", "p", "q", "dp", "dq", "qi", "oth", "k"}
        signing_key = False
        for key in keys:
            key = object_value(key, "JWKS key")
            require(not (private_fields & key.keys()), "JWKS must never expose private key fields")
            kid = key.get("kid")
            nonempty(kid, "JWKS key.kid")
            require(kid not in ids, "JWKS key IDs must be distinct")
            ids.add(kid)
            if key.get("kty") == "EC" and key.get("crv") == "P-256":
                for coordinate in ("x", "y"):
                    value = key.get(coordinate)
                    require(isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_-]{43}", value),
                            f"P-256 public JWKS key requires a base64url {coordinate} coordinate")
                signing_key = signing_key or key.get("alg", "ES256") == "ES256" and key.get("use", "sig") == "sig"
        require(signing_key, "JWKS must contain an ES256 signing key")

    def run(self, profile, catalog, oauth, expected_version, ambiguous_url):
        self.case("health and version", self.health, expected_version)
        self.case("root redirect", self.redirect, "/", "/docs" if profile == "docs" else "/episodes/73-yards", 303)
        self.case("documentation canonical redirect", self.redirect, "/docs/", "/docs", 308)
        self.case("documentation and agent discovery", self.docs_discovery)
        self.case("Lexicon index", self.schema_index)
        for name in SCHEMAS:
            self.case(f"Lexicon {name}", self.schema, name)
        self.case("unknown Lexicon returns 404", lambda: self.get(f"{DOC_INDEX}/{NSID}{MISSING}.json", status=404))
        if profile == "docs":
            for path in ("/episodes/73-yards", "/api/episodes/73-yards", "/api/catalog",
                         "/api/resolve", "/oauth-client-metadata.json", "/.well-known/jwks.json"):
                self.case(f"docs mode excludes {path}", lambda: self.get(path, status=404))
            return
        self.case("episode canonical redirect", self.redirect, "/episodes/73-yards/?x=1", "/episodes/73-yards?x=1", 308)
        self.case("API canonical redirect", self.redirect, "/api/episodes/73-yards/", "/api/episodes/73-yards", 308)
        self.case("unknown episode returns 404", lambda: self.get(f"/api/episodes/{MISSING}", status=404))
        for fixture in EPISODES:
            episode_id, _, _, _, _, _, sources = fixture
            payload = self.case(f"episode API {episode_id}", self.episode, fixture, catalog)
            watch_url = sources[0][2] if sources[0][0] == "apple-tv" else None
            self.case(f"public page {episode_id}", self.page, episode_id, watch_url)
            self.case(f"resolve own page {episode_id}", self.resolve,
                      f"{self.origin}/episodes/{episode_id}?ref=conformance#discussion", payload, "episode-page", episode_id)
            for source, external_id, url in sources:
                self.case(f"resolve {source} for {episode_id}", self.resolve, url, payload, source, external_id)
            if episode_id == "73-yards":
                self.case("BBC programme variant", self.resolve,
                          "https://www.bbc.co.uk/programmes/m001zpzs?ref=conformance", payload, "bbc", "m001zpzs")
                self.case("IMDb query and fragment variant", self.resolve,
                          IMDB + "?ref_=tt_ov_inf#metadata", payload, "imdb", "tt28704625")
            elif episode_id == "widows-bay-s01e01":
                self.case("Apple TV locale variant", self.resolve,
                          watch_url.replace("/us/episode/", "/gb/episode/").split("?", 1)[0],
                          payload, "apple-tv", sources[0][1])
        for label, url in (
            ("missing input", None),
            ("unparseable input", "not a link"),
            ("unsupported scheme", IMDB.replace("https:", "ftp:", 1)),
            ("untrusted host", "https://www.imdb.com.example.invalid/title/tt28704625/"),
            ("userinfo", "https://someone@www.imdb.com/title/tt28704625/"),
            ("nondefault port", "https://www.imdb.com:8888/title/tt28704625/"),
            ("related path", IMDB + "reviews/"),
            ("unknown title", "https://www.imdb.com/title/tt01234567/"),
            ("unknown own page", f"{self.origin}/episodes/{MISSING}"),
            ("overlong input", IMDB + "?" + "x" * 2000),
        ):
            self.case(f"unresolved {label}", self.unresolved, url)
        if ambiguous_url:
            self.case("ambiguous fixture returns 409", self.ambiguous, ambiguous_url)
        self.case(f"{catalog} catalog", self.catalog, catalog)
        if oauth:
            self.case("public confidential OAuth metadata and JWKS", self.oauth_metadata)


def parse_origin(value):
    try:
        origin = urlsplit(value)
        port = origin.port
    except ValueError as error:
        raise argparse.ArgumentTypeError("expected an HTTP(S) origin") from error
    if (origin.scheme not in ("http", "https") or not origin.hostname or origin.username is not None
            or origin.password is not None or origin.path not in ("", "/") or "?" in value or "#" in value
            or any(char.isspace() or ord(char) < 32 for char in value) or "\\" in value or port == 0):
        raise argparse.ArgumentTypeError("expected an HTTP(S) origin with no path, credentials, query or fragment")
    host = origin.hostname
    if ":" in host:
        host = f"[{host}]"
    default_port = 443 if origin.scheme == "https" else 80
    authority = f"{host}:{port}" if port and port != default_port else host
    return f"{origin.scheme}://{authority}"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--base-url", required=True, type=parse_origin, help="target HTTP(S) origin")
    parser.add_argument("--profile", required=True, choices=("docs", "app"), help="deployment under test")
    parser.add_argument("--catalog", choices=("demo", "live"),
                        help="required for app; demo requires null AT URIs, live checks a DID and public manifest")
    parser.add_argument("--oauth", action="store_true", help="check the optional confidential pilot OAuth metadata")
    parser.add_argument("--ambiguous-url", help="check a URL seeded with conflicting claims in your app fixture")
    parser.add_argument("--expect-version", help="require a particular advertised SemVer")
    parser.add_argument("--timeout", type=float, default=5, help="per socket operation timeout in seconds (default: 5)")
    parser.add_argument("--json", action="store_true", help="emit one JSON result instead of human-readable lines")
    args = parser.parse_args()
    if (args.profile == "app") != bool(args.catalog):
        parser.error("--catalog is required for app and unavailable for docs")
    if args.oauth and (args.profile != "app" or not args.base_url.startswith("https://")):
        parser.error("--oauth requires the app profile and an HTTPS origin")
    if args.ambiguous_url and (args.profile != "app" or len(args.ambiguous_url) > 2000):
        parser.error("--ambiguous-url requires the app profile and a URL of at most 2000 characters")
    if args.expect_version and not SEMVER.fullmatch(args.expect_version):
        parser.error("--expect-version must be SemVer")
    if not 0 < args.timeout <= 60:
        parser.error("--timeout must be greater than 0 and at most 60 seconds")

    suite = Suite(args.base_url, args.timeout, args.json)
    suite.run(args.profile, args.catalog, args.oauth, args.expect_version, args.ambiguous_url)
    failures = sum(result["status"] == "fail" for result in suite.results)
    passed = len(suite.results) - failures
    if args.json:
        print(json.dumps({
            "profile": args.profile, "catalog": args.catalog, "oauth": args.oauth,
            "version": suite.version, "passed": passed, "failed": failures, "checks": suite.results,
        }))
    else:
        profile = f"{args.profile}/{args.catalog}" if args.catalog else args.profile
        print(f"{profile}: {passed} passed, {failures} failed")
    return int(failures != 0)


if __name__ == "__main__":
    raise SystemExit(main())
