"""Verify Vector1 Lab's sealed forecasts yourself.

    python verify_vector1.py            (downloads https://vector1.ai/lab/registry.json)
    python verify_vector1.py file.json  (checks a saved copy)

Each forecast's hash covers its content plus the previous forecast's hash. This script recomputes
every hash it can see in full (graded forecasts publish their content) and checks that every link
in the chain points at the hash before it. Pending forecasts publish only their hash until graded."""
import hashlib, json, sys, urllib.request

FIELDS = ("model", "model_version", "target", "unit", "issued_at", "valid_for", "horizon", "quantiles", "point", "inputs", "note")


def canon(d):
    return json.dumps({k: d.get(k) for k in FIELDS} | {"id": d["id"], "prev": d["prev"]}, sort_keys=True, separators=(",", ":"))


def main():
    src = sys.argv[1] if len(sys.argv) > 1 else "https://vector1.ai/lab/registry.json"
    data = json.load(open(src)) if not src.startswith("http") else json.load(urllib.request.urlopen(src))
    prev, full, bad = "genesis", 0, 0
    for i, e in enumerate(data["entries"]):
        if e["prev"] != prev:
            print(f"BROKEN LINK at entry {i + 1}"); bad += 1
        if "quantiles" in e:
            full += 1
            if hashlib.sha256(canon(e).encode()).hexdigest() != e["hash"]:
                print(f"CONTENT DOES NOT MATCH HASH at entry {i + 1}"); bad += 1
        prev = e["hash"]
    print(f"{len(data['entries'])} seals, {full} checked in full, chain head {prev[:12]}: {'OK' if not bad else 'FAILED'}")
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main())
