from pathlib import Path
import hashlib,json,platform,subprocess,sys
root=Path(__file__).resolve().parent
scripts=['verify_single_u_mode_theorem.py','verify_full_cyclic_rigidity.py','independent_checker.py','adversarial_counterexample_search.py']
runs=[]
for name in scripts:
    p=subprocess.run([sys.executable,name],cwd=root,text=True,capture_output=True,timeout=1200)
    runs.append({'script':name,'returncode':p.returncode,'stdout':p.stdout.strip(),'stderr':p.stderr.strip()})
    if p.returncode:
        raise SystemExit(name+' FAILED\n'+p.stdout+'\n'+p.stderr)
files={}
for p in sorted(root.iterdir()):
    if p.is_file() and p.name not in {'manifest.json','SHA256SUMS.txt'}:
        files[p.name]=hashlib.sha256(p.read_bytes()).hexdigest()
manifest={'status':'PASS','date':'2026-07-21','python':platform.python_version(),'platform':platform.platform(),'runs':runs,'files_sha256':files}
(root/'manifest.json').write_bytes((json.dumps(manifest,indent=2)+'\n').encode('utf-8'))
allfiles=sorted(p for p in root.iterdir() if p.is_file() and p.name!='SHA256SUMS.txt')
ledger='\n'.join(hashlib.sha256(p.read_bytes()).hexdigest()+' *'+p.name for p in allfiles)+'\n'
(root/'SHA256SUMS.txt').write_bytes(ledger.encode('utf-8'))
print(json.dumps({'status':'PASS','runs':len(runs),'hashed_files':len(allfiles),'manifest_sha256':hashlib.sha256((root/'manifest.json').read_bytes()).hexdigest(),'ledger_sha256':hashlib.sha256((root/'SHA256SUMS.txt').read_bytes()).hexdigest()},indent=2))
