#!/usr/bin/env python3
import json,hashlib,sys,datetime,os
from pathlib import Path
PROJECT='gacmai_20260718_075153';CONCEPT_SHA='0ac2600ec1e964494a688426ed3f59e1bd0d46d4f34982756cfb539a29bed7a0'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 if len(sys.argv)!=5:raise SystemExit('usage: promote_outline.py OUTLINE STRUCTURAL SEMANTIC INDEPENDENT_AUDIT')
 op,sp,mp,ap=map(Path,sys.argv[1:]);o=json.loads(op.read_text());s=json.loads(sp.read_text());m=json.loads(mp.read_text());a=json.loads(ap.read_text());h=sha(op)
 checks={
  'project':o.get('project_id')==PROJECT,
  'concept':o.get('source_concept_sha256')==CONCEPT_SHA,
  'structural':s.get('status')=='passed' and s.get('outline_sha256')==h,
  'semantic':m.get('status')=='passed' and m.get('sha256')==h,
  'independent':a.get('verdict')=='pass' and (a.get('source',{}).get('sha256') or a.get('source_outline_sha256') or a.get('audited_artifacts',{}).get('source_outline',{}).get('sha256'))==h,
  'parts_beats':s.get('parts')==12 and s.get('beats')==144,
  'word_target':14000<=s.get('target_words',0)<=15000
 }
 if not all(checks.values()):raise SystemExit(json.dumps({'status':'blocked','checks':checks},ensure_ascii=False))
 root=Path(os.environ.get('PROJECT_ROOT','/data/video-pipeline/GacMaiAudio/project/'+PROJECT));art=root/'artifacts';dst=art/'outline_canonical.json';tmp=art/'.outline_canonical.json.tmp';tmp.write_bytes(op.read_bytes());os.replace(tmp,dst)
 rec={'status':'promoted','project_id':PROJECT,'outline_sha256':h,'concept_sha256':CONCEPT_SHA,'structural_receipt_sha256':sha(sp),'semantic_receipt_sha256':sha(mp),'independent_audit_sha256':sha(ap),'checks':checks,'promoted_at':datetime.datetime.now(datetime.timezone.utc).isoformat()};rp=art/'outline_promotion_receipt.json';rp.write_text(json.dumps(rec,ensure_ascii=False,indent=2)+'\n')
 status=json.loads((root/'status.json').read_text());status.update({'stage':'story_generation','canonical_outline_sha256':h,'outline_status':'promoted','updated_at':rec['promoted_at']});(root/'status.json').write_text(json.dumps(status,ensure_ascii=False,indent=2)+'\n');print(json.dumps(rec,ensure_ascii=False))
if __name__=='__main__':main()
