"""Create an immutable private evidence manifest and sanitized public summary."""
import hashlib, json, os, subprocess, sys
from pathlib import Path
root=Path(__file__).parent
result=subprocess.run([sys.executable,str(root/'verify.py')],check=True,capture_output=True,text=True)
summary=json.loads(result.stdout)
for lane in ('B','C'):
    d=root/'private'/lane
    for name in ('auth.json','current.json','lease.json'):
        if (d/name).exists(): raise RuntimeError('Temporary credential/lease remains')
    cleanup=json.loads((d/'cleanup-source.json').read_text())
    if cleanup['removed_own_copied_source_files']!=959: raise RuntimeError('Own source cleanup missing')
for d in (root/'private').rglob('*'):
    if d.is_symlink(): raise RuntimeError('Evidence symlink')
    os.chmod(d,0o700 if d.is_dir() else 0o600)
os.chmod(root/'private',0o700)
files=[]
for p in sorted((root/'private').rglob('*')):
    if p.is_file() and p.name!='manifest.json':
        files.append({'path':str(p.relative_to(root/'private')),'bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'mode':oct(p.stat().st_mode&0o777)})
manifest={'schema':1,'status':summary['status'],'files':files,'credentials_excluded':['auth.json','current.json','lease.json'],'source_snapshots_not_archived':True}
with (root/'private'/'manifest.json').open('x') as f: json.dump(manifest,f,ensure_ascii=False,indent=2)
os.chmod(root/'private'/'manifest.json',0o600)
summary['private_manifest_sha256']=hashlib.sha256((root/'private'/'manifest.json').read_bytes()).hexdigest()
summary['private_file_count']=len(files)
with (root/'summary.json').open('x') as f: json.dump(summary,f,ensure_ascii=False,indent=2)
print(json.dumps(summary,ensure_ascii=False,indent=2))
