#!/usr/bin/env python3
from pathlib import Path
import json,hashlib,subprocess,sys,datetime
P='gacmai_20260717_184527';R=Path('/data/video-pipeline/GacMaiAudio/project')/P;A=R/'artifacts';S=A/'scripts';OUT=A/'story_package_candidate.json';OUTLINE='6648cdf5473d3bf72c759726357ecfcf480feea01424569e866fced1abb6e7e9'
if len(sys.argv)!=4:raise SystemExit('usage: assemble_story BATCH1 BATCH2 BATCH3')
if OUT.exists():raise SystemExit('candidate already exists; refuse overwrite')
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
paths=[Path(x) for x in sys.argv[1:]];ranges=[(1,4),(5,8),(9,12)];sources=[];parts=[]
for p,(a,b) in zip(paths,ranges):
 d=json.loads(p.read_text())
 if d.get('project_id')!=P or d.get('title')!='Mùa Nở Không Có Tên' or d.get('outline_sha256')!=OUTLINE or d.get('part_range')!=[a,b]:raise SystemExit(f'identity mismatch {p}')
 cp=subprocess.run(['python3',str(S/'validate_batch.py'),str(p),str(a),str(b)],capture_output=True,text=True);v=json.loads(cp.stdout)
 if cp.returncode or v.get('status')!='passed':raise SystemExit(f'batch validation failed {p}: {v}')
 parts.extend(d['parts']);sources.append({'path':str(p),'sha256':sha(p),'part_range':[a,b],'validation':v})
story={'project_id':P,'title':'Mùa Nở Không Có Tên','outline_sha256':OUTLINE,'pov':'Nguyễn Lam Chi','named_characters':['Nguyễn Lam Chi','Trần Vĩnh Phúc','Lê Thu Nguyệt','Phạm Hữu Tường','Đỗ Khánh An','Vũ Minh Triết'],'sources':[{k:v for k,v in x.items() if k!='validation'} for x in sources],'parts':parts};OUT.write_text(json.dumps(story,ensure_ascii=False,indent=2)+'\n');h=sha(OUT)
checks={}
for name,cmd in [('validation',['python3',str(S/'validate_story.py'),str(OUT)]),('duplication',['python3',str(S/'audit_duplication.py'),str(OUT)])]:
 cp=subprocess.run(cmd,capture_output=True,text=True);checks[name]=json.loads(cp.stdout)
 if cp.returncode or checks[name].get('status')!='passed':
  receipt={'status':'failed','story_sha256':h,'sources':sources,'checks':checks,'failed_gate':name};(A/'story_assembly_receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2)+'\n');print(json.dumps(receipt,ensure_ascii=False));raise SystemExit(1)
receipt={'status':'passed','story_sha256':h,'sources':sources,'checks':checks,'created_at':datetime.datetime.now(datetime.timezone.utc).isoformat()};(A/'story_assembly_receipt.json').write_text(json.dumps(receipt,ensure_ascii=False,indent=2)+'\n');print(json.dumps(receipt,ensure_ascii=False))
