"""Read pinned LongCat documents without weights or model execution."""

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()


def get(url):
    with urllib.request.urlopen(
        urllib.request.Request(url, headers={"User-Agent": "CloutSourceAudit/1.0"}), timeout=40
    ) as r:
        b = r.read(1000001)
        if len(b) > 1000000:
            raise ValueError("Document limit exceeded")
        return b


if a.baseline:
    spec = json.loads(a.baseline.read_text())["documents"]
else:
    rev = "f0e4c43c5ef74b011ff71570fbfc2bdffbc9ab06"
    dr = "aaf57d03a3edfbd9de457d2872417a92f149a91d"
    spec = [
        {
            "name": n,
            "url": f"https://raw.githubusercontent.com/meituan-longcat/LongCat-Image/{rev}/{n}",
        }
        for n in ["README.md", "LICENSE", "scripts/inference_edit.py"]
    ]
    for n in [
        "src/diffusers/pipelines/longcat_image/pipeline_longcat_image.py",
        "src/diffusers/pipelines/longcat_image/pipeline_longcat_image_edit.py",
        "LICENSE",
    ]:
        spec.append(
            {
                "name": "diffusers/" + n,
                "url": f"https://raw.githubusercontent.com/huggingface/diffusers/{dr}/{n}",
            }
        )
    for name in ["LongCat-Image-Edit", "LongCat-Image-Edit-Turbo"]:
        m = json.loads(get("https://huggingface.co/api/models/meituan-longcat/" + name))
        spec.append(
            {
                "name": name + "/README.md",
                "url": f"https://huggingface.co/meituan-longcat/{name}/resolve/{m['sha']}/README.md",
            }
        )
result = []
for x in spec:
    h = hashlib.sha256(get(x["url"])).hexdigest()
    if a.baseline and h != x["sha256"]:
        raise ValueError("Source changed " + x["name"])
    result.append({"name": x["name"], "url": x["url"], "sha256": h})
print(
    json.dumps({"scope": "Read only document audit no model test", "documents": result}, indent=2)
)
