from pathlib import Path
import json,hashlib,sys,stat
P=Path(__file__).resolve().parent
TARGET=P/'finish-seal.json'
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()
def verify(manifest):
    actual={str(p.relative_to(P)) for p in P.rglob('*') if p.is_file() and p!=TARGET}
    assert actual==set(manifest['files'])
    for path in [P,*P.rglob('*')]:
        assert not path.is_symlink()
        assert stat.S_IMODE(path.stat().st_mode)==(0o700 if path.is_dir() else 0o600)
    for name,m in manifest['files'].items():
        path=P/name;assert path.stat().st_size==m['bytes'] and sha(path)==m['sha256']
    assert sha(P.parent/'first-phase/seal.json')==manifest['immutable_first_phase_seal_file_sha256']
    assert not (P.parent/'source').exists()
    assert not list(P.rglob('tokens.json')) and not list(P.rglob('cache'))
if '--verify' in sys.argv:
    result=json.loads(TARGET.read_text());verify(result)
else:
    assert not TARGET.exists()
    for path in [P,*P.rglob('*')]:
        assert not path.is_symlink()
        path.chmod(0o700 if path.is_dir() else 0o600)
    files={str(p.relative_to(P)):{'bytes':p.stat().st_size,'sha256':sha(p),'mode':'0600'} for p in sorted(P.rglob('*')) if p.is_file() and p!=TARGET}
    result={'task_id':'ZHCTPROMPT-20260928-SMART-CANTEEN-DUAL-DB-COMPAT-PLAN','scope':'Original three store survey writers; tested branches partial only','HTTP_B':24,'HTTP_C':24,'HTTP_finish_B':18,'HTTP_finish_C':20,'immutable_first_phase_seal_file_sha256':sha(P.parent/'first-phase/seal.json'),'final_model_sha256':'a81a7a4eff91aec6745517a26a8794f8ccda4edf633c993406d5c557525d6afd','files':files}
    TARGET.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');TARGET.chmod(0o600);verify(result)
print(json.dumps({'files':len(result['files']),'public_files':sum(not x.startswith('private/') for x in result['files']),'private_files':sum(x.startswith('private/') for x in result['files']),'seal_file_sha256':sha(TARGET),'SHA_bytes_modes_nolink_exact':True}))
