import hashlib,json,os,stat
from pathlib import Path
HERE=Path(__file__).resolve().parent;assert not (HERE/'manifest.json').exists(),'No reseal'
prior=[]
for folder,name in [(HERE.parent,'manifest-blocked4.json'),(HERE.parent/'retry1','manifest.json'),(HERE.parent,'strict-candidate-manifest.json')]:
    m=json.loads((folder/name).read_text())
    for r in m['files']:
        p=folder/r['path'];assert p.is_file() and not p.is_symlink() and p.stat().st_size==r['bytes'] and hashlib.sha256(p.read_bytes()).hexdigest()==r['sha256'] and oct(stat.S_IMODE(p.stat().st_mode))==r['mode'],r['path']
    prior.append({'manifest':str((folder/name).relative_to(HERE.parent)),'file_sha256':hashlib.sha256((folder/name).read_bytes()).hexdigest(),'unchanged_files':len(m['files'])})
mapping=json.loads((HERE/'source-lock.json').read_text());assert len(mapping)==959;assert hashlib.sha256((HERE/'source-lock.json').read_bytes()).hexdigest()=='49b1a564de5a93dcd0385659a3d79f2e92256970b7fd7cc0a1adb8d482ccdd57';canonical=hashlib.sha256(json.dumps(mapping,sort_keys=True,separators=(',',':')).encode()).hexdigest();assert canonical=='a6c3604ca13eddf6dce5c9d3e7c8ed61e56406164ccbff23971fc9d764f069c5'
rows=[]
for p in sorted(HERE.rglob('*')):
    rel=p.relative_to(HERE);assert not p.is_symlink()
    if 'private' in rel.parts:os.chmod(p,0o700 if p.is_dir() else 0o600)
    if p.is_file():b=p.read_bytes();rows.append({'path':str(rel),'bytes':len(b),'sha256':hashlib.sha256(b).hexdigest(),'mode':oct(stat.S_IMODE(p.stat().st_mode))})
out={'scope':'Root959 candidate p/m lists four HTTP only','prior_seals_unchanged':prior,'source_application_count':959,'source_canonical_sha256':canonical,'oracle_dependency_sha256':hashlib.sha256((HERE.parent/'oracle-original.py').read_bytes()).hexdigest(),'files':rows};out['seal_sha256']=hashlib.sha256(json.dumps(out,ensure_ascii=False,sort_keys=True,separators=(',',':')).encode()).hexdigest();f=HERE/'manifest.json';f.write_text(json.dumps(out,ensure_ascii=False,indent=2)+'\n');print(json.dumps({'files':len(rows),'file_sha256':hashlib.sha256(f.read_bytes()).hexdigest(),'canonical_sha256':out['seal_sha256'],'prior_unchanged_files':sum(r['unchanged_files'] for r in prior)}))
