"""Check authored chapter order and text hashes, not a delivered audiobook."""
from pathlib import Path
import json,copy,hashlib,sys
def validate(d):
    rows=d['chapters']
    if [r['chapter_id'] for r in rows]!=['C01','C02','C03'] or [r['order'] for r in rows]!=[1,2,3]:raise ValueError('missing,duplicate or reordered chapter')
    for r in rows:
        if r['text_version']!=d['text_version']:raise ValueError('stale text version')
        if hashlib.sha256(r['text'].encode()).hexdigest()!=r['text_sha256']:raise ValueError('text hash mismatch')
        if r['audio']['status']!='planned_not_generated' or any(r['audio'][k] is not None for k in ['duration_seconds','sha256']):raise ValueError('not this planning fixture')
        if r['local_start_seconds'] is not None or r['cumulative_start_seconds'] is not None:raise ValueError('timing is unknown before audio production')
    return True
if __name__=='__main__':
    p=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).with_name('audiobook-original-three-chapter-plan.json')
    d=json.loads(p.read_text(encoding='utf-8'));assert validate(d);rejected=0
    for kind in ['missing','duplicate','order','stale']:
        b=copy.deepcopy(d)
        if kind=='missing':b['chapters'].pop()
        elif kind=='duplicate':b['chapters'][1]=copy.deepcopy(b['chapters'][0])
        elif kind=='order':b['chapters']=list(reversed(b['chapters']))
        else:b['chapters'][1]['text_version']='old'
        try:validate(b)
        except ValueError:rejected+=1
    assert rejected==4
    print(json.dumps({'chapters':3,'text_hashes_verified':3,'invalid_mutations_rejected':rejected,'actual_audio_files':0,'timing_measured':False},indent=2))
