"""Download the published recorded result; no model or service is started."""
import hashlib
import json
from pathlib import Path
from urllib.request import urlopen
from uuid import uuid4

BASE = "https://aureon-foundation.vercel.app"


def fetch(path, limit):
    with urlopen(BASE + path, timeout=30) as response:
        data = response.read(limit + 1)
    if len(data) > limit:
        raise ValueError("Response exceeded its expected size")
    return data


def main():
    receipt = json.loads(fetch("/examples/thailand/receipt.json", 65536))
    assert receipt["schema"] == "aureon.public_recorded_result.v1"
    verified = {}
    for name in ("class_map.tif", "valid_mask.tif"):
        item = receipt["artifacts"][name]
        path = "/examples/thailand/" + name
        if item["url"] != path or not 0 < item["bytes"] <= 16 * 1024 * 1024:
            raise ValueError("Unexpected artifact declaration")
        data = fetch(path, item["bytes"])
        if (len(data) != item["bytes"] or
                hashlib.sha256(data).hexdigest() != item["sha256"]):
            raise ValueError("Verification failed: " + name)
        verified[name] = data

    output = Path("aureon-example-" + uuid4().hex[:8])
    output.mkdir(exist_ok=False)
    for name, data in verified.items():
        (output / name).write_bytes(data)
        print("Verified:", name)
    (output / "receipt.json").write_text(json.dumps(receipt, indent=2))
    print("Results:", output)
    return output


if __name__ == "__main__":
    main()
