from collections import Counter
import gzip
import hashlib
import io
import json
import re
from urllib.request import Request, urlopen

BASE = "https://localmark.ai"

def download(path, limit):
    request = Request(BASE + path, headers={"User-Agent": "LocalMarkDatasetExample/1.0"})
    with urlopen(request, timeout=30) as response:
        data = response.read(limit + 1)
    if len(data) > limit:
        raise ValueError("Download exceeds this example's size limit")
    return data

manifest = json.loads(download("/data/latest.json", 100_000))
filename = manifest["gzip_file"]
if not re.fullmatch(r"[0-9]{4}-[0-9]{2}-[0-9]{2}\.jsonl\.gz", filename):
    raise ValueError("Unexpected snapshot filename")
compressed = download("/data/" + filename, 32_000_000)
if hashlib.sha256(compressed).hexdigest() != manifest["gzip_sha256"]:
    raise ValueError("Compressed-file checksum mismatch; do not analyse it")

states = Counter()
agent_ids = set()
rows = 0
unpacked = 0
with gzip.GzipFile(fileobj=io.BytesIO(compressed)) as source:
    while True:
        line = source.readline(1_000_001)
        if not line:
            break
        unpacked += len(line)
        if unpacked > 64_000_000 or len(line) > 1_000_000:
            raise ValueError("Uncompressed data exceeds this example's limits")
        record = json.loads(line)
        if record["agent_id"] in agent_ids:
            raise ValueError("Duplicate agent ID")
        agent_ids.add(record["agent_id"])
        rows += 1
        probe = record["observations"].get("read_only_a2a_probe") or {}
        states[probe.get("state") or "not_recorded"] += 1
if rows != manifest["record_count"]:
    raise ValueError("Record count does not match the manifest")
print("Snapshot:", manifest["snapshot_date"], "records:", rows)
for state, count in states.most_common():
    print(state, count)
print("Credit: Data: LocalMark (localmark.ai), CC BY 4.0, snapshot", manifest["snapshot_date"])
