"""Verify the checksum, published DOI and selected browser release files."""
from concurrent.futures import ThreadPoolExecutor
from hashlib import sha256
import json
from pathlib import Path
from urllib.request import Request, urlopen

root = Path(__file__).parent
doi = "10.5281/zenodo.24650089"
origin = "https://agentmapfactory.com/"

def get(url):
    request = Request(url, headers={"User-Agent": "AgentEd public artifact verification", "Cache-Control": "no-cache"})
    with urlopen(request, timeout=30) as response:
        return response.geturl(), response.read()

def document(url):
    return json.loads(get(url)[1])

digest, name = (root/"SHA256SUMS").read_text(encoding="ascii").split()
assert name == "evidence.json"
payload = (root/name).read_bytes()
assert sha256(payload).hexdigest() == digest
evidence = json.loads(payload)
published = document("https://zenodo.org/api/records/24650089")
assert published["doi"] == doi and published["metadata"]["version"] == "0.1"
assert published["metadata"]["publication_date"] == "2026-11-29"
assert published["metadata"]["creators"][0]["name"] == "Eissens, Raynor"
registry = document("https://api.datacite.org/dois/"+doi)["data"]["attributes"]
assert registry["state"] == "findable"
assert get("https://doi.org/"+doi)[0] == "https://zenodo.org/records/24650089"
latest = document(published["links"]["latest"])
print(f"Verified published v0.1 DOI. Zenodo now lists v{latest['metadata']['version']} as latest ({latest['doi']}).")

manifest = document(origin+"archive.json")
world = next(w for w in manifest["worlds"] if w["id"]=="festival")
assert manifest["established"] == "2026-11-30" and world["released"] == "2026-12-01"
captured = next(r["result"] for r in evidence if r["label"]=="festival compiled browser capture")
assert world["provenance"]["nativeMapSha256"]==captured["native_map_sha256"]
assert world["provenance"]["bspCaptureSha256"]==captured["bsp_capture_sha256"]
assert world["provenance"]["t3dReadbackSha256"]==captured["t3d_readback_sha256"]

receipt = next(r["result"] for r in evidence if r["label"]=="December 1 sitemap and public world receipt")
def verify_file(entry):
    name = entry["file"]
    route = name[:-len("index.html")] if name.endswith("index.html") else name
    _, live = get(origin+route)
    return name, len(live)==entry["bytes"] and sha256(live).hexdigest()==entry["sha256"]

with ThreadPoolExecutor(max_workers=8) as pool:
    results = list(pool.map(verify_file, receipt["selected_http_files"]))
changes = [name for name, equal in results if not equal]
print(f"{len(results)-len(changes)}/{len(results)} live files match the retained December 1 SHA-256 receipt.")
if changes:
    print("Live versions differ from the retained receipt: "+", ".join(changes))

