"""Audit pinned SeFi source documents without accessing gated checkpoint files."""

import argparse
import hashlib
import json
import urllib.request
from pathlib import Path

p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--baseline", type=Path)
a = p.parse_args()
rev = "f5d85ef656b974a25f2e45fce4a17a3eeeea7eef"
files = [
    "README.md",
    "LICENSE",
    "sefi/cli.py",
    "sefi/pipeline.py",
    "sefi/resolution.py",
    "sefi/registry.py",
    "sefi/runner.py",
]
spec = (
    json.loads(a.baseline.read_text())["documents"]
    if a.baseline
    else [
        {"name": f, "url": f"https://raw.githubusercontent.com/jmliu206/SeFi-Image/{rev}/{f}"}
        for f in files
    ]
)
result = []
for x in spec:
    req = urllib.request.Request(x["url"], headers={"User-Agent": "CloutSourceAudit/1.0"})
    with urllib.request.urlopen(req, timeout=40) as r:
        body = r.read(1000001)
        if len(body) > 1000000:
            raise ValueError("Document limit exceeded")
    digest = hashlib.sha256(body).hexdigest()
    if a.baseline and digest != x["sha256"]:
        raise ValueError("Source changed " + x["name"])
    result.append({"name": x["name"], "url": x["url"], "sha256": digest})
print(
    json.dumps(
        {
            "scope": "Read only source audit no gated files weights or model inference",
            "documents": result,
        },
        indent=2,
    )
)
