"""Check the published frozen A3 aggregate without a database (Python standard library)."""
import argparse
import json
from pathlib import Path


def verify(data, *, original_provenance=True):
    assert data["road"] == "A3" and data["direction"] == "outboundFromTown", "Wrong selection"
    assert data["timeZone"] == "Europe/Luxembourg" and data["unit"] == "km/h", "Wrong units/time zone"
    assert data["period"] == {"start": "2026-07-23T16:23:00+02:00", "end": "2026-09-03T19:13:00+02:00"}, "Wrong evaluation window"
    digest = data["source"]["sha256"]
    assert len(digest) == 64 and all(c in "0123456789abcdef" for c in digest), "Invalid declared CSV hash"
    if original_provenance:
        assert digest == "c81c7dbeb5a8a0cedad6a2be9f9ba4ebc10b76df853a11af6dc00a116e683f9c", "Wrong declared CSV provenance"
    for name in ("weekdays", "weekend"):
        series = data["series"][name]
        assert [p["hour"] for p in series] == list(range(24)), "Expected 24 ordered hours per series"
        for p in series:
            assert isinstance(p["observations"], int) and p["observations"] > 0, "Missing observation count"
            assert isinstance(p["speedKmh"], (float, int)) and 0 < p["speedKmh"] < 250, "Invalid mean speed"
    assert data["series"]["weekdays"][8] == {"hour": 8, "speedKmh": 68.3, "observations": 4600}, "Weekday reference differs"
    assert data["series"]["weekend"][8] == {"hour": 8, "speedKmh": 101.2, "observations": 1706}, "Weekend reference differs"
    assert data["series"]["weekend"][14]["speedKmh"] == 91.9, "Weekend minimum reference differs"


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("aggregate", type=Path)
    parser.add_argument("--compare", type=Path, help="Compare all 48 points with another aggregate")
    args = parser.parse_args()
    data = json.loads(args.aggregate.read_text())
    verify(data)
    print("PASS: 48 hourly points; weekday 08:00 = 68.3 km/h (n=4600); weekend = 101.2 km/h (n=1706).")
    if args.compare:
        other = json.loads(args.compare.read_text())
        # A database re-export can format/order CSV differently while yielding
        # identical aggregate values. Preserve the public input's hash assertion,
        # but compare the reproduced values independently of its CSV bytes.
        verify(other, original_provenance=False)
        assert data["series"] == other["series"], "Reproduced series differ"
        print("PASS: all 48 speeds and observation counts match the comparison export.")
    print("Scope: aggregate checks only; this does not validate raw measurements or collection coverage.")
