"""Audit pinned Runway SDK documents without credentials or provider requests."""

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 = "d21a613791516edfd734914fc3e638e3f54f9f0c"
files = [
    "README.md",
    "LICENSE",
    "CHANGELOG.md",
    "src/resources/workflow-invocations.ts",
    "src/resources/workflows.ts",
    "src/lib/polling.ts",
]
spec = (
    json.loads(a.baseline.read_text())["documents"]
    if a.baseline
    else [
        {"name": f, "url": f"https://raw.githubusercontent.com/runwayml/sdk-node/{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:
        b = r.read(1000001)
        if len(b) > 1000000:
            raise ValueError("Document limit exceeded")
    digest = hashlib.sha256(b).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 SDK source audit no provider API or generation request",
            "documents": result,
        },
        indent=2,
    )
)
