#!/usr/bin/env python3
"""Verify the branding-release manifest and independently check archive CRCs."""
from pathlib import Path
import hashlib,json,sys,zipfile
root=Path(__file__).resolve().parent
expected=json.loads((root/'SHA256SUMS.json').read_text(encoding='utf-8'))
actual={p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file() and p.name!='SHA256SUMS.json'}
errors=[]
if actual!=set(expected):
    errors.append({'unlisted':sorted(actual-set(expected)), 'missing':sorted(set(expected)-actual)})
for rel,want in expected.items():
    p=root/rel
    if not p.is_file():continue
    h=hashlib.sha256()
    with p.open('rb') as f:
        for b in iter(lambda:f.read(1048576),b''):h.update(b)
    if h.hexdigest()!=want:errors.append({'hash_mismatch':rel})
    if p.suffix.lower()=='.zip':
        try:
            with zipfile.ZipFile(p) as z:
                damaged=z.testzip()
                if damaged:errors.append({'archive_crc':rel,'member':damaged})
        except Exception as exc:errors.append({'archive_error':rel,'error':str(exc)})
print(json.dumps({'passed':not errors,'payload_files_checked':len(expected),'errors':errors},indent=2))
sys.exit(0 if not errors else 1)
