#!/usr/bin/env python3
"""Verify the published 205-store study packet using only the standard library."""

from __future__ import annotations

import csv
import hashlib
import json
from collections import Counter
from pathlib import Path


ROOT = Path(__file__).resolve().parent


def read_json(name: str):
    return json.loads((ROOT / name).read_text())


def sha256(name: str) -> str:
    return hashlib.sha256((ROOT / name).read_bytes()).hexdigest()


def main() -> None:
    with (ROOT / "sampling-frame.csv").open(newline="") as handle:
        frame = list(csv.DictReader(handle))
    survey = read_json("platform-survey-2026-08-31.json")
    imports = read_json("import-outcomes-2026-08-31.json")
    summary = read_json("summary.json")
    manifest = read_json("source-manifest.json")

    frame_keys = [row["key"] for row in frame]
    survey_keys = [row["key"] for row in survey["results"]]
    import_keys = [row["key"] for row in imports]

    assert len(frame_keys) == 205
    assert len(set(frame_keys)) == 205
    assert Counter(row["state"] for row in frame) == {"IL": 88, "PA": 117}
    assert set(frame_keys) == set(survey_keys) == set(import_keys)

    statuses = Counter(row["status"] for row in imports)
    accepted_product_bearing = sum(
        row["status"] == "ok" and row["fetched"] > 0 for row in imports
    )
    replication = summary["replication_2026_08_31"]

    assert dict(sorted(statuses.items())) == replication["import_status_counts"]
    assert accepted_product_bearing == replication["accepted_product_bearing"] == 26
    assert round(accepted_product_bearing / 205 * 100, 1) == 12.7
    assert survey["summary"]["platform_and_catalog"] == 39
    assert summary["historical_2026_08_09"]["markup_probe_threshold_positive"] == 3

    for name, expected in manifest["files"].items():
        assert sha256(name) == expected["sha256"], f"SHA-256 mismatch: {name}"
        assert (ROOT / name).stat().st_size == expected["bytes"], f"size mismatch: {name}"

    print(
        "verified: 205 rows (88 IL, 117 PA); 39 platform-prefilter positives; "
        "26 accepted product-bearing results; all published hashes match"
    )


if __name__ == "__main__":
    main()
