#!/usr/bin/env python3
from pathlib import Path
import json,hashlib,datetime
P='gacmai_20260717_184527';R=Path('/data/video-pipeline/GacMaiAudio/project')/P;A=R/'artifacts'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
manifest=A/'outline_release_manifest.json';outline=A/'locked_outline_canonical.json';pending=A/'writer_dispatch_contract_pending.json';dst=A/'writer_dispatch_contract.json'
for p in (manifest,outline,pending):
 if not p.exists():raise SystemExit(f'missing {p.name}')
if dst.exists():raise SystemExit('writer contract already active')
m=json.loads(manifest.read_text());d=json.loads(pending.read_text());h=sha(outline)
if m.get('status')!='passed' or m.get('writer_dispatch_authorized') is not True or m.get('outline_sha256')!=h:raise SystemExit('outline release mismatch')
if d.get('outline_sha256')!=h or d.get('writer_dispatch_authorized') is not False:raise SystemExit('pending contract mismatch')
d['status']='authorized';d['writer_dispatch_authorized']=True;d['outline_release_manifest_sha256']=sha(manifest);d['authorized_at']=datetime.datetime.now(datetime.timezone.utc).isoformat();dst.write_text(json.dumps(d,ensure_ascii=False,indent=2)+'\n')
receipt={'status':'passed','outline_sha256':h,'contract_sha256':sha(dst),'manifest_sha256':sha(manifest),'activated_at':d['authorized_at']};(A/'writer_dispatch_authorization.json').write_text(json.dumps(receipt,indent=2)+'\n');print(json.dumps(receipt))
