"""Recompute the station results using public JSON and Python's standard library."""
import argparse
from collections import defaultdict
from datetime import date, datetime, time, timedelta
from fractions import Fraction
from functools import lru_cache
from hashlib import sha256
import json
import math
from pathlib import Path
import sys
from urllib.request import Request, urlopen
from zoneinfo import ZoneInfo

PRAGUE = ZoneInfo("Europe/Prague")
AXES = ("economic", "cultural")
ROLES = {"externi": {"guest", "commentator"}, "hoste": {"guest"}, "komentatori": {"commentator"},
         "redakce": {"staff"}, "moderatori": {"presenter"}, "vsichni": {"guest", "commentator", "staff", "presenter"}}


def check(actual, expected, field):
    if isinstance(expected, (int, float, Fraction)) and not isinstance(expected, bool):
        equal = type(actual) in (int, float, Fraction) and math.isclose(actual, expected, rel_tol=1e-10, abs_tol=1e-8)
    else:
        equal = actual == expected
    if isinstance(expected, bool):
        equal = actual is expected
    if not equal:
        raise ValueError(f"{field}: published {actual!r}, expected {expected!r}")


def instant(value):
    stamp = datetime.fromisoformat(value)
    if stamp.utcoffset() is None:
        raise ValueError(f"Missing UTC offset in {value}")
    return int(stamp.timestamp())


def midnight(day):
    return int(datetime.combine(day, time.min, PRAGUE).timestamp())


def dated_evidence(records, person, episode, axis):
    app = episode["appearances"][person]
    made = episode["made"]
    reviews = {r["subject"]: (key, r) for key, r in records["assessment"].items()
               if r["axis"] == axis and made and r["since"] <= made and (not r["until"] or made < r["until"])}
    subject = app["represents"] if app["capacity"] in ("institution", "politician") else None
    if app["capacity"] == "independent" or (app["capacity"] == "politician" and
                                            reviews.get(person, (None, {}))[1].get("status") == "scored"):
        subject = person
    key, review = reviews.get(subject, (None, {}))
    if review.get("score") is not None:
        for field in ("quote", "url", "author", "date"):
            if not (review.get("evidence") or {}).get(field):
                raise ValueError(f"Missing {field} for assessment {key}")
    return dict(subject=subject, assessment=key, score=review.get("score"), status=review.get("status", "awaiting"))


def station_credits(data, lower, upper):
    """Reference implementation: inspect whole elementary intervals on the single station timeline."""
    records = data["records"]
    airings = []
    segments = []
    boundaries = {lower, upper}
    originals = set()
    for airing, air in records["airing"].items():
        if air["station"] != data["station"]:
            continue
        start, end = instant(air["start"]), instant(air["end"])
        if start >= upper or end <= lower:
            continue
        airings.append((start, end, air["episode"]))
        boundaries.update((max(lower, start), min(upper, end)))
        people = records["episode"][air["episode"]]["appearances"]
        if air["kind"] == "first" and lower <= start < upper:
            originals.update((airing, p) for p in people)
        for seg in air["segments"]:
            if not 0 <= seg["start"] < seg["end"] <= end - start:
                raise ValueError(f"Segment outside airing {airing}")
            offsets = [Fraction(str(seg[k])) if isinstance(seg[k], float) else seg[k] for k in ("start", "end")]
            left, right = max(lower, start + offsets[0]), min(upper, start + offsets[1])
            if left < right:
                segments.append((left, right, airing, seg))
                boundaries.update((left, right))

    amounts = defaultdict(Fraction)
    estimates = defaultdict(Fraction)
    edges = sorted(boundaries)
    for left, right in zip(edges, edges[1:]):
        # Programme identity can conflict even when only one programme has credits.
        if len({episode for start, end, episode in airings if start <= left and right <= end}) != 1:
            continue
        by_airing = defaultdict(list)
        for start, end, airing, seg in segments:
            if start <= left and right <= end:
                by_airing[airing].append(seg)
        claims = {}
        for airing, parts in by_airing.items():
            if any(not part["complete"] for part in parts):
                continue
            people = {p for part in parts for p in part["people"]}
            if people:
                claims[airing] = people
        identities = {(records["airing"][a]["episode"], frozenset(people)) for a, people in claims.items()}
        if len(identities) != 1:
            continue
        episode, people = identities.pop()
        owner = min(claims, key=lambda a: (records["airing"][a]["kind"] != "first", a))
        apps = records["episode"][episode]["appearances"]
        speakers = {p for p in people if set(apps[p]["roles"]) != {"presenter"}}
        for person in people:
            divisor = len(speakers) if person in speakers else 1
            amount = Fraction(right - left, divisor)
            amounts[owner, person] += amount
            if divisor > 1 or any(seg["estimated"] and person in seg["people"]
                                  for a in claims for seg in by_airing[a]):
                estimates[owner, person] += amount

    rows = {}
    for airing, person in sorted(amounts.keys() | originals):
        episode = records["airing"][airing]["episode"]
        ep = records["episode"][episode]
        app = ep["appearances"][person]
        rows[airing, person] = dict(episode=episode, person=person, roles=app["roles"], represents=app["represents"],
                                    seconds=amounts[airing, person], estimated=estimates[airing, person],
                                    original=(airing, person) in originals,
                                    axes={axis: dated_evidence(records, person, ep, axis) for axis in AXES})
    return rows


def published_credits(data, lower, upper):
    """Observed named editions publish allocated credits with evidence, without individual segment boundaries."""
    records = data["records"]
    rows = {}
    for row in data["views"]["prehled"]["filters"]["vsichni"]["credits"]:
        air = records["airing"][row["airing"]]
        ep = records["episode"][air["episode"]]
        person = row["person"]
        app = ep["appearances"][person]
        start, end = instant(air["start"]), instant(air["end"])
        check(air["station"], data["station"], "credit station")
        if not 0 <= row["estimated"] <= row["seconds"] <= min(end, upper) - max(start, lower) + 1e-8:
            raise ValueError(f"Invalid window credit for {row['airing']}/{person}")
        if lower <= start and end <= upper:
            ledger = data["ledger"][row["airing"] + "/" + person]
            for field in ("estimated", "seconds"):
                check(row[field], ledger[field], "ledger " + field)
        rows[row["airing"], person] = dict(
            episode=air["episode"], person=person, roles=app["roles"], represents=app["represents"],
            seconds=Fraction(str(row["seconds"])), estimated=Fraction(str(row["estimated"])),
            original=air["kind"] == "first" and lower <= start < upper,
            axes={axis: dated_evidence(records, person, ep, axis) for axis in AXES})
    return rows


def calculate_axis(rows, axis, weighting, complete):
    bins = {score: Fraction() for score in range(-2, 3)}
    missing = defaultdict(Fraction)
    people, firsts = set(), set()
    for row in rows:
        applied = row["axes"][axis]
        score = applied["score"]
        weight = row["seconds"] if weighting == "time" else int(row["original"])
        if score is not None and row["original"]:
            firsts.add((row["person"], row["episode"]))
        if weight:
            if score is None:
                missing[applied["status"]] += weight
            else:
                people.add(row["person"])
                bins[score] += weight
    scored = sum(bins.values())
    total = scored + sum(missing.values())
    coverage = scored / total if total else None
    failures = []
    if len(people) < 3:
        failures.append("guests")
    if len(firsts) < 10:
        failures.append("appearances")
    if not total or 5 * scored < 3 * total:
        failures.append("coverage")
    if not complete:
        failures.append("schedule")
    weighted = sum(k * v for k, v in bins.items())
    expected = dict(total=total, guests=len(people), appearances=len(firsts), coverage=coverage,
                    reviewed=(total - missing.get("awaiting", 0)) / total if total else None,
                    index=None if failures else weighted / scored, reasons=failures)
    denominator = total - missing.get("inapplicable", 0)
    sensitivity = None if failures else [
        (weighted + bound * (denominator - scored)) / denominator for bound in (-2, 2)]
    return dict(expected, bins={str(k): v for k, v in bins.items()}, missing=dict(missing), sensitivity=sensitivity)


def compare_measure(reading, expected, path):
    for field, value in expected.items():
        if isinstance(value, dict):
            check(set(reading[field]), set(value), f"{path}.{field} keys")
            for key, count in value.items():
                check(reading[field][key], count, f"{path}.{field}.{key}")
        elif isinstance(value, list) and field == "sensitivity":
            check(len(reading[field]), len(value), path + ".sensitivity length")
            for i, bound in enumerate(value):
                check(reading[field][i], bound, f"{path}.sensitivity[{i}]")
        else:
            check(reading[field], value, f"{path}.{field}")


def verify_sample(data, slots, lower, upper):
    audit = data["researchWindow"]
    by_show = defaultdict(list)
    used = set()
    for row in data["airtime"]:
        if "externalGuests" not in row or "slotId" not in row:
            raise ValueError("This earlier release does not expose guest counts per transmission")
        label = f"{row['show']} at {row['start']}"
        key = (row["recording"], instant(row["start"]))
        if key in used:
            raise ValueError(f"Duplicate timing evidence for {label}")
        used.add(key)
        start, end = key[1], instant(row["end"])
        day = datetime.fromtimestamp(start, PRAGUE)
        check(row["schedule"], f"https://api.rozhlas.cz/data/v2/schedule/day/{day:%Y/%m/%d}/plus.json", label + " schedule")
        if not 0 <= row["minutes"] <= (min(upper, end) - max(start, lower)) / 60 + 1e-8:
            raise ValueError(f"External minutes outside broadcast window for {label}")
        if type(row["externalGuests"]) is not int or row["externalGuests"] < 0:
            raise ValueError(f"Invalid external guest count for {label}")
        if row["slotId"] is not None:
            ep, slot = slots[row["slotId"]]
            check((row["recording"], row["show"], start, end, row["schedule"]),
                  (ep["source"], ep["show"], instant(slot["start"]), instant(slot["end"]), slot["source"]), label)
        if row["externalGuests"]:
            by_show[row["show"]].append(row)
        else:
            check(row["minutes"], 0, label)
    check(set(audit["shows"]), set(by_show), "audited programmes")
    def compare(rows, totals, label):
        counts = [r["externalGuests"] for r in rows]
        if type(totals["guests"]) is not int or not max(counts, default=0) <= totals["guests"] <= sum(counts):
            raise ValueError(f"{label} unique guest count is incompatible with individual airings")
        check(totals["episodes"], len({r["recording"] for r in rows}), label + ".episodes")
        check(totals["airings"], len(rows), label + ".airings")
        check(totals["minutes"], sum(r["minutes"] for r in rows), label + ".minutes")
    for label, rows in by_show.items():
        compare(rows, audit["shows"][label], label)
    compare([r for group in by_show.values() for r in group], audit, "audited sample")
    check(sum(audit["organizationMinutes"].values()), audit["representedMinutes"], "represented minutes")
    check(audit["scheduleSlots"], data["slots"], "audited schedule")
    for axis in AXES:
        for scenario in ("approved", "includingProposals"):
            result = audit[scenario][axis]
            minutes = result["scoredMinutes"]
            if not 0 <= minutes <= audit["minutes"]:
                raise ValueError(f"{axis}.{scenario} scored minutes outside denominator")
            check(result["coverage"], minutes / audit["minutes"] if audit["minutes"] else None,
                  f"{axis}.{scenario}.coverage")
            check(result["missingMinutes"], max(0, 0.6 * audit["minutes"] - minutes), f"{axis}.{scenario}.missing")
        # This aggregate format supports withheld indices and carries no public scored contributions.
        approved = audit["approved"][axis]
        for field in ("scoredMinutes", "scoredGuests", "firstAppearances"):
            check(approved[field], 0, f"{axis}.approved.{field}")
        reading = data["views"]["prehled"]["filters"]["externi"]["summary"]["axes"][axis]["time"]
        for field, value in (("total", audit["minutes"] * 60), ("index", None), ("coverage", approved["coverage"]),
                             ("guests", 0), ("appearances", 0)):
            check(reading[field], value, f"{axis}.time.{field}")
        check(reading["bins"], {str(k): 0 for k in range(-2, 3)}, f"{axis}.time.bins")
        check(reading["reviewed"], None, f"{axis}.time.reviewed")
        check(reading["sensitivity"], None, f"{axis}.time.sensitivity")
        check(reading["missing"]["unclassified"], audit["minutes"] * 60, f"{axis}.time.unclassified")
        reasons = ["guests", "appearances", "coverage"]
        if data["recovered"] != len(data["days"]):
            reasons.append("schedule")
        check(reading["reasons"], reasons, f"{axis}.time.reasons")
    return {"airingsWithExternalGuests": audit["airings"],
            "airingsWithPositiveMinutes": sum(r["minutes"] > 0 for r in data["airtime"]),
            "estimatedMinutes": audit["minutes"]}


def verify_trends(data):
    """Check calendar windows once per series. Synthetic historical weights can be replayed from segments."""
    available = {date.fromisoformat(d["date"]) for d in data["archive"] if d["available"]}
    end = date.fromisoformat(data["last"])
    earliest = min(available, default=date.fromisoformat(data["first"]))
    history_days = min(730, max(30, (end - earliest).days + 1))
    # The fixture has 120 days. Cache the same station allocation across programmes and role filters.
    @lru_cache(maxsize=256)
    def allocated(first, last):
        return station_credits(data, midnight(first), midnight(last + timedelta(days=1)))

    @lru_cache(maxsize=2048)
    def coverage(last, length):
        return sum(last - timedelta(days=i) in available for i in range(length))

    verified = 0
    checked_empty = set()
    for slug, view in data["views"].items():
        if view["kind"] not in ("station", "show"):
            continue
        length = 90 if view["kind"] == "show" else 30
        for role, selection in view["filters"].items():
            shared = selection.get("trendWindow")
            points = data["emptyTrends"][str(shared)] if shared is not None else selection["trend"]
            check(len(points), history_days, f"{slug}/{role} history length")
            for axis in AXES:
                check(selection["summary"]["axes"][axis]["time"]["index"], points[-1][axis],
                      f"{slug}/{role} latest {axis} index")
            if shared is not None:
                check(shared, length, slug + ".trendWindow")
                if data["ledger"]:
                    raise ValueError("Shared empty trend cannot represent an editorial ledger")
                if shared in checked_empty:
                    continue
                checked_empty.add(shared)
            for i, point in enumerate(points):
                last = end - timedelta(days=len(points) - 1 - i)
                first = last - timedelta(days=length - 1)
                path = f"{slug}/{role}/{last}"
                recovered = coverage(last, length)
                check((point["start"], point["end"], point["length"], point["days"]),
                      (str(first), str(last), length, recovered), path + " window")
                if recovered < length or shared is not None:
                    values = dict.fromkeys(AXES)
                    expected_rows = {}
                elif data["mode"] == "demo":
                    expected_rows = {key: r for key, r in allocated(first, last).items()
                                     if ROLES[role].intersection(r["roles"]) and (view["kind"] == "station" or
                                     data["records"]["episode"][r["episode"]]["show"] == slug.split("/", 1)[1])}
                    values = {a: calculate_axis(expected_rows.values(), a, "time", True)["index"] for a in AXES}
                else:
                    # Named historical segment boundaries were not released. Their calendar coverage is checkable.
                    continue
                for axis, value in values.items():
                    check(point[axis], value, path + "." + axis)
                packed = point.get("credits", [])
                if any(value is not None for value in values.values()):
                    check(len(packed), len(expected_rows), path + " window credit count")
                    seen = set()
                    for airing, person, seconds, estimated, original in packed:
                        row = expected_rows[airing, person]
                        seen.add((airing, person))
                        check(seconds, row["seconds"], path + " seconds")
                        check(estimated, row["estimated"], path + " estimated seconds")
                        check(original, row["original"], path + " premiere")
                    check(seen, set(expected_rows), path + " window credits")
                else:
                    check(packed, [], path + " withheld credits")
                verified += 1
    return verified


def verify_selections(filters, rows, complete, audit=None):
    for role, roles in ROLES.items():
        selection = filters[role]
        expected = {key: row for key, row in rows.items() if roles.intersection(row["roles"])}
        published = {(r["airing"], r["person"]): r for r in selection["credits"]}
        check(len(published), len(selection["credits"]), role + " unique credits")
        check(set(published), set(expected), role + " credit identities")
        for key, row in expected.items():
            for field, value in row.items():
                check(published[key][field], value, f"{role}.{key}.{field}")
        result = selection["summary"]
        if role == "externi" and audit is not None:
            check(result["seconds"], audit["minutes"] * 60, "audited seconds")
            check(result["voiceCount"], audit["guests"], "reported guest count")
        else:
            check(result["seconds"], sum(r["seconds"] for r in expected.values()), role + ".seconds")
            check(result["estimated"], sum(r["estimated"] for r in expected.values()), role + ".estimated")
            voices = defaultdict(Fraction)
            for r in expected.values():
                voices[r["person"]] += r["seconds"]
            check(result["voiceCount"], len(voices), role + ".voiceCount")
            check(result["originals"], len({(r["episode"], r["person"]) for r in expected.values() if r["original"]}),
                  role + ".originals")
            check([p for p, _ in result["voices"]], sorted(voices, key=lambda p: (-voices[p], p)), role + ".voices")
            for person, seconds in result["voices"]:
                check(seconds, voices[person], role + "." + person + ".seconds")
            check(result["largestShare"], max(voices.values()) / sum(voices.values())
                  if sum(voices.values()) else None, role + ".largestShare")
        for axis in AXES:
            for weight in ("time", "episode"):
                if audit is not None and role == "externi" and weight == "time":
                    continue
                measure = calculate_axis(expected.values(), axis, weight, complete)
                compare_measure(result["axes"][axis][weight], measure, f"{role}.{axis}.{weight}")


def verify_detail_views(data, station_month, last):
    first = last - timedelta(days=89)
    station_quarter = station_credits(data, midnight(first), midnight(last + timedelta(days=1)))
    available = {d["date"] for d in data["archive"] if d["available"]}
    for slug, view in data["views"].items():
        kind = view["kind"]
        if kind == "station":
            continue
        subject = slug.split("/", 1)[1]
        length = 90 if kind == "show" else 30
        first = last - timedelta(days=length - 1)
        check(view["first"], str(first), slug + ".first")
        complete = all(str(first + timedelta(days=i)) in available for i in range(length))
        selected = {}
        for key, row in (station_quarter if kind == "show" else station_month).items():
            ep = data["records"]["episode"][row["episode"]]
            if ((kind == "person" and row["person"] == subject) or
                (kind == "institution" and row["represents"] == subject) or
                (kind == "show" and ep["show"] == subject) or
                (kind == "journalist" and row["person"] != subject
                 and "presenter" in ep["appearances"].get(subject, {}).get("roles", []))):
                selected[key] = row
        try:
            verify_selections(view["filters"], selected, complete)
        except ValueError as exc:
            raise ValueError(f"{slug}: {exc}") from exc


def verify_interview_seconds(window):
    """Measure consecutive spans once when matched audio is present and no recorded insert is playing."""
    begin, end = window["intro"][1], window["exit"][0]
    events = defaultdict(lambda: [0, 0])
    for kind, spans in enumerate((window["matchedReferenceWindows"], window.get("recordedInsertWindows", []))):
        for left, right in spans:
            if type(left) is not int or type(right) is not int or not begin <= left < right <= end:
                raise ValueError("Interview interval outside the introduction and farewell")
            events[left][kind] += 1
            events[right][kind] -= 1
    previous, matched, inserts, total = begin, 0, 0, 0
    for position, (matches_change, inserts_change) in sorted(events.items()):
        if matched and not inserts:
            total += position - previous
        matched += matches_change
        inserts += inserts_change
        previous = position
    check(window["verifiedCoreSeconds"], total, "interview verifiedCoreSeconds")
    return total


def verify(data):
    check(data["version"], 1, "version")
    if data["mode"] not in ("observed", "demo"):
        raise ValueError("Unknown release mode")
    first, last = (date.fromisoformat(data[k]) for k in ("first", "last"))
    check((last - first).days + 1, 30, "station window length")
    check([d["date"] for d in data["days"]], [str(first + timedelta(days=i)) for i in range(30)], "schedule dates")
    available = [d for d in data["days"] if d["available"]]
    check(data["recovered"], len(available), "available days")
    check(data["slots"], sum(d["slots"] for d in available) if available else None, "scheduled slots")
    slots = {}
    sources = set()
    for ep in data["broadcasts"]:
        if ep["source"] in sources:
            raise ValueError(f"Duplicate recording {ep['source']}")
        sources.add(ep["source"])
        for slot in ep["slots"]:
            if slot["id"] in slots:
                raise ValueError(f"Duplicate slot {slot['id']}")
            slots[slot["id"]] = (ep, slot)
    summary = {"mode": data["mode"], "first": str(first), "last": str(last), "scheduled": data["slots"],
               "matchedRecordings": len(sources), "matchedAirings": len(slots)}
    station_runs = defaultdict(list)
    for air in data["records"]["airing"].values():
        station_runs[air["station"], air["episode"]].append(air)
    for (station, episode), runs in station_runs.items():
        firsts = [instant(air["start"]) for air in runs if air["kind"] == "first"]
        if len(firsts) > 1 or (firsts and any(instant(air["end"]) <= firsts[0] for air in runs)):
            raise ValueError(f"Conflicting first broadcast for {episode} on {station}")
    measurements = [window for _, slot in slots.values() for window in slot.get("interviewCues", {}).get("windows", [])
                    if "verifiedCoreSeconds" in window or "matchedReferenceWindows" in window]
    summary["interviewMeasurements"] = {"interviews": len(measurements),
                                         "verifiedCoreSeconds": sum(verify_interview_seconds(w) for w in measurements)}
    lower, upper = midnight(first), midnight(last + timedelta(days=1))
    audit = data["researchWindow"]
    if audit is not None:
        check((audit["station"], audit["first"], audit["last"]), (data["station"], str(first), str(last)), "sample window")
        expected_counts = [[d[k] for k in ("date", "slots", "coveredSeconds", "repeatSlots", "unknownRepeatSlots", "missingShowId")]
                           for d in available]
        check(audit["archiveCounts"], expected_counts, "audit schedule provenance")
        check(audit["scheduleDays"], len(available), "audited days")
        check(data["mode"], "observed", "sample mode")
        summary.update(verify_sample(data, slots, lower, upper))
    elif data["airtime"]:
        raise ValueError("Timing ledger has no audit window")
    inventory = data.get("programmeInventory")
    if inventory is not None:
        for key, expected in (("scheduled", data["slots"]), ("matched", len(slots)), ("withExternal", audit["airings"])):
            check(sum(row[key] for row in inventory.values()), expected, f"programme inventory {key}")

    if data.get("scheduleEntries") is not None:
        summary["archivedSchedule"] = verify_schedule(data, data["scheduleEntries"], allow_partial=True)
    archive = {row["date"]: row for row in data["archive"]}
    additional_days = []
    for key, item in data.get("additionalSchedules", {}).items():
        day = date.fromisoformat(key)
        if first <= day <= last or not item["entries"]:
            raise ValueError(f"Invalid additional schedule for {key}")
        check(item["schedule"]["date"], key, "additional schedule date")
        check(item["schedule"]["available"], True, "additional schedule availability")
        if key in archive:
            check(item["schedule"], archive[key], f"{key} archived daily counts")
        additional_days.append(verify_day(data, day, item["entries"]))
    if additional_days:
        summary["additionalSchedules"] = additional_days
    if data["mode"] == "demo":
        if any("segments" not in a for a in data["records"]["airing"].values()):
            raise ValueError("This earlier demo does not include the segments needed for an independent replay")
        rows = station_credits(data, lower, upper)
        summary["creditBasis"] = "publicSegments"
    else:
        rows = published_credits(data, lower, upper)
        summary["creditBasis"] = "auditedAggregate" if audit is not None else "reportedCredits"
    filters = data["views"]["prehled"]["filters"]
    verify_selections(filters, rows, len(available) == 30, audit)
    if data["mode"] == "demo":
        verify_detail_views(data, rows, last)
    summary["axes"] = {axis: filters["externi"]["summary"]["axes"][axis]["time"]["index"] for axis in AXES}
    summary["verifiedTrendPoints"] = verify_trends(data)
    return summary


def read_url(url):
    request = Request(url, headers={"User-Agent": "SlantIndex-public-verifier/1"})
    with urlopen(request, timeout=20) as response:
        return response.read()


def validate_schedule_entry(row):
    if type(row["id"]) is not int or row["id"] <= 0:
        raise ValueError(f"Invalid schedule slot ID {row['id']!r}")
    if not isinstance(row["title"], str) or not row["title"].strip():
        raise ValueError(f"Missing schedule title for slot {row['id']}")
    if row["repeat"] is not None and type(row["repeat"]) is not bool:
        raise ValueError(f"Invalid repeat flag for slot {row['id']}")
    if row["showId"] is not None and type(row["showId"]) is not int:
        raise ValueError(f"Invalid show ID for slot {row['id']}")


def source_entries(response):
    entries = {}
    rows = response["data"]
    if not isinstance(rows, list) or not rows:
        raise ValueError("Missing or empty source schedule")
    for row in rows:
        check(row["station"], "plus", "source station")
        edition = row.get("edition")
        if edition is None or edition == []:
            show_id = None
        elif isinstance(edition, dict):
            show_id = edition.get("id")
        else:
            raise ValueError(f"Invalid edition for slot {row['id']}")
        entry = dict(id=row["id"], title=row["title"], start=row["since"], end=row["till"],
                     repeat=row.get("repetition"), showId=show_id)
        validate_schedule_entry(entry)
        if entry["id"] in entries:
            check(entry, entries[entry["id"]], f"duplicate source slot {entry['id']}")
        entries[entry["id"]] = entry
    return list(entries.values())


def verify_day(data, day, entries):
    """Reconstruct start counts and clipped elapsed coverage from individual schedule entries."""
    check(data["mode"], "observed", "source comparison mode")
    extra = data.get("additionalSchedules", {}).get(day.isoformat(), {})
    published = next((d for d in data["days"] if d["date"] == day.isoformat() and d["available"]), extra.get("schedule"))
    if not published:
        raise ValueError(f"No recovered schedule for {day} in this edition")
    lower, upper = midnight(day), midnight(day + timedelta(days=1))
    url = f"https://api.rozhlas.cz/data/v2/schedule/day/{day:%Y/%m/%d}/plus.json"
    check(published["source"], url, f"{day} schedule source")
    slots = {}
    for row in entries:
        validate_schedule_entry(row)
        start, end = instant(row["start"]), instant(row["end"])
        if end <= start or start >= upper or end <= lower:
            raise ValueError(f"Source slot outside {day}")
        if row["id"] in slots:
            raise ValueError(f"Duplicate schedule slot {row['id']}")
        slots[row["id"]] = (start, end, row["repeat"], row["showId"])
    starts = [row for row in slots.values() if lower <= row[0] < upper]
    check(published["slots"], len(starts), f"{day} slots")
    check(published["repeatSlots"], sum(row[2] is True for row in starts), f"{day} repeat flags")
    check(published["unknownRepeatSlots"], sum(row[2] is None for row in starts), f"{day} unknown repeat flags")
    check(published["missingShowId"], sum(row[3] is None for row in starts), f"{day} missing show ID")
    last_end, seconds = lower, 0
    for start, end, _, _ in sorted(slots.values(), key=lambda r: r[:2]):
        clipped_end = min(end, upper)
        seconds += max(0, clipped_end - max(start, last_end))
        last_end = max(last_end, clipped_end)
    check(published["coveredSeconds"], seconds, f"{day} covered seconds")
    check(published["secondsInDay"], upper-lower, f"{day} elapsed seconds in day")
    matched = 0
    matched_ids = set()
    for airing in extra.get("airings", []):
        key = airing["id"]
        if key in matched_ids or key not in slots or not (lower <= instant(airing["start"]) < upper):
            raise ValueError(f"Invalid additional recording match {key}")
        matched_ids.add(key)
        check((instant(airing["start"]), instant(airing["end"]), airing["repeat"]), slots[key][:3],
              f"ČRo slot {key}")
        check(airing["schedule"], url, f"ČRo slot {key} schedule source")
        check((airing["externalGuests"], airing["estimatedMinutes"]), (None, None), "additional schedule timing")
        matched += 1
    for episode in data["broadcasts"]:
        for slot in episode["slots"]:
            if lower <= instant(slot["start"]) < upper:
                source = slots.get(slot["id"])
                check((instant(slot["start"]), instant(slot["end"]), slot["repeat"]),
                      source[:3] if source else None, f"ČRo slot {slot['id']}")
                check(slot["source"], url, f"ČRo slot {slot['id']} schedule source")
                matched += 1
    # Excerpts can cross into a different scheduled hour while retaining the original archive URL.
    evidence = [(r["slotId"], r["start"], r["schedule"]) for r in
                (*data.get("excerpts", []), *data.get("stationCues", []))]
    evidence.extend((part["slotId"], part["start"], clip["schedule"]) for clip in data.get("excerpts", [])
                    for segment in clip["segments"] if (part := segment.get("aircheck")))
    for slot_id, start, schedule in evidence:
        if lower <= instant(start) < upper:
            check(slots.get(slot_id, (None,))[0], instant(start), f"ČRo partial audio slot {slot_id}")
            check(schedule, url, f"ČRo partial audio source {slot_id}")
    return {"day": str(day), "scheduled": len(starts), "matched": matched, "coveredSeconds": seconds}


def read_document(location):
    return read_url(location) if location.startswith("https://") else Path(location).read_bytes()


def verify_summary(data, result, summary):
    check(summary["dataSha256"], result["dataSha256"], "data.json SHA-256")
    check(summary["version"], 1, "summary version")
    for key in ("mode", "station"):
        check(summary[key], data[key], "summary " + key)
    check(summary["period"], {"first": data["first"], "last": data["last"], "timeZone": "Europe/Prague"}, "summary period")
    check(summary["schedule"], {"availableDays": data["recovered"], "slots": result["scheduled"]}, "summary schedule")
    check(summary["matched"], {"recordings": result["matchedRecordings"], "airings": result["matchedAirings"]}, "summary matches")
    if "interviewMeasurements" in summary or result["interviewMeasurements"]["interviews"]:
        check(summary["interviewMeasurements"], result["interviewMeasurements"], "summary interview measurements")
    for axis in AXES:
        reading = data["views"]["prehled"]["filters"]["externi"]["summary"]["axes"][axis]["time"]
        check(summary["axes"][axis], {key: reading[key] for key in ("index", "coverage", "reasons")}, "summary " + axis)
    audit = data["researchWindow"]
    check(summary["auditedSample"], None if audit is None else
          {"guests": audit["guests"], "recordings": audit["episodes"], "airings": result["airingsWithExternalGuests"],
           "estimatedMinutes": result["estimatedMinutes"]}, "summary audited sample")


def verify_schedule(data, days, *, allow_partial=False):
    check(data["mode"], "observed", "source comparison mode")
    inventory = defaultdict(lambda: {"scheduled": 0, "matched": 0, "withExternal": 0})
    matched = {slot["id"] for ep in data["broadcasts"] for slot in ep["slots"]}
    external = {row["slotId"] for row in data["airtime"] if row["externalGuests"]}
    available = {d["date"] for d in data["days"] if d["available"]}
    if allow_partial:
        if not days or not set(days).issubset(available):
            raise ValueError("Invalid partial schedule evidence dates")
    else:
        check(set(days), available, "schedule evidence dates")
    verified_matches = 0
    for key, entries in days.items():
        verified_matches += verify_day(data, date.fromisoformat(key), entries)["matched"]
        for row in entries:
            if datetime.fromtimestamp(instant(row["start"]), PRAGUE).date().isoformat() == key:
                title = inventory[row["title"]]
                title["scheduled"] += 1
                title["matched"] += int(row["id"] in matched)
                title["withExternal"] += int(row["id"] in external)
    if data.get("programmeInventory") is not None and set(days) == available:
        check(set(data["programmeInventory"]), set(inventory), "inventory titles from ČRo")
        for title, counts in inventory.items():
            check(data["programmeInventory"][title], counts, "ČRo title " + title)
    return {"days": len(days), "titles": len(inventory), "matched": verified_matches}


def compare_archived(data, days):
    archived = {**(data.get("scheduleEntries") or {}),
                **{key: item["entries"] for key, item in data.get("additionalSchedules", {}).items()}}
    for day, entries in days.items():
        if day not in archived:
            continue
        expected = {r["id"]: r for r in entries}
        saved = {r["id"]: r for r in archived[day]}
        check(set(saved), set(expected), f"{day} source IDs")
        for key, row in expected.items():
            check(saved[key], row, f"{day} source slot {key}")


def main():
    cli = argparse.ArgumentParser(description=__doc__)
    cli.add_argument("release", help="Downloaded data.json or its HTTPS URL")
    cli.add_argument("--summary", help="Also compare the site's summary.json (local file or HTTPS URL)")
    source = cli.add_mutually_exclusive_group()
    source.add_argument("--schedule-dir", type=Path,
                        help="Check every recovered day and the title inventory against saved YYYY-MM-DD.json responses")
    source.add_argument("--day", type=date.fromisoformat, help="Compare a recovered day with the broadcaster")
    cli.add_argument("--schedule-file", type=Path, help="Use a saved ČRo response with --day")
    args = cli.parse_args()
    if args.schedule_file and not args.day:
        cli.error("--schedule-file needs --day")
    try:
        body = read_document(args.release)
        data = json.loads(body)
        result = verify(data)
        result["dataSha256"] = sha256(body).hexdigest()
        if args.summary:
            verify_summary(data, result, json.loads(read_document(args.summary)))
        if args.schedule_dir:
            days = {d["date"]: source_entries(json.loads((args.schedule_dir / (d["date"] + ".json")).read_bytes()))
                    for d in data["days"] if d["available"]}
            result["sourceComparison"] = verify_schedule(data, days)
            compare_archived(data, days)
        if args.day:
            if data["mode"] != "observed" or (str(args.day) not in data.get("additionalSchedules", {})
                    and not any(d["date"] == str(args.day) and d["available"] for d in data["days"])):
                raise ValueError("Choose a recovered day from an observed edition")
            url = f"https://api.rozhlas.cz/data/v2/schedule/day/{args.day:%Y/%m/%d}/plus.json"
            response = json.loads(args.schedule_file.read_bytes()) if args.schedule_file else json.loads(read_url(url))
            entries = source_entries(response)
            result["sourceComparison"] = verify_day(data, args.day, entries)
            compare_archived(data, {str(args.day): entries})
    except (OSError, ValueError, KeyError, TypeError, IndexError, ArithmeticError) as exc:
        print(json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False), file=sys.stderr)
        return 1
    print(json.dumps({"ok": True, **result}, ensure_ascii=False, indent=2))
    return 0


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