import json, sys, urllib.request, pathlib, hashlib
lock, outdir = sys.argv[1], pathlib.Path(sys.argv[2])
outdir.mkdir(parents=True, exist_ok=True)
missing = []
for line in pathlib.Path(lock).read_text().splitlines():
    line = line.strip()
    if not line or line.startswith('#'): continue
    name, ver = line.split('==')
    url = f"https://pypi.org/pypi/{name}/{ver}/json"
    try:
        with urllib.request.urlopen(url, timeout=60) as r:
            d = json.load(r)
    except Exception as e:
        missing.append((name, ver, f"metadata: {e}")); continue
    sd = [u for u in d['urls'] if u['packagetype'] == 'sdist']
    if not sd:
        missing.append((name, ver, "no sdist published")); continue
    u = sd[0]
    dest = outdir / u['filename']
    if dest.exists() and dest.stat().st_size == u['size']:
        print("have", u['filename']); continue
    try:
        with urllib.request.urlopen(u['url'], timeout=300) as r, open(dest, 'wb') as f:
            data = r.read(); f.write(data)
        if hashlib.sha256(data).hexdigest() != u['digests']['sha256']:
            missing.append((name, ver, "sha256 mismatch")); dest.unlink()
        else:
            print("got ", u['filename'])
    except Exception as e:
        missing.append((name, ver, f"download: {e}"))
if missing:
    print("\n--- NO SDIST / FAILED ---")
    for m in missing: print(f"{m[0]}=={m[1]}  ({m[2]})")
