"""Read only synthetic development databases and export provisioning errors and control state."""
import os,pathlib,sqlite3,json
root=pathlib.Path(os.environ['EVIDENCE_SCRATCH'])
for side,key in [('before','EVIDENCE_BASE'),('after','EVIDENCE_HEAD')]:
    checkout=pathlib.Path(os.environ[key]);run=pathlib.Path((root/(side+'-run.txt')).read_text())
    db=sqlite3.connect('file:'+str(checkout/'.t3/userdata/statev2.sqlite')+'?mode=ro',uri=True)
    rows=[]
    for kind,raw in db.execute("select event_type,payload_json from orchestration_events where event_type='turn-item.updated'"):
        obj=json.loads(raw)
        if obj.get('type')=='error' and 'branch_already_exists' in json.dumps(obj):
            rows.append({'threadId':obj['threadId'],'status':obj['status'],'failure':obj['failure']})
    text=json.dumps(rows,indent=2).replace(str(run/'sample-repo'),'$SAMPLE_REPO').replace(str(checkout),'$CHECKOUT')
    (root/(side+'-provisioning-errors.json')).write_text(text+'\n')
    for src,dest in [('transcript.txt',side+'-transcript.txt'),('terminal.cast',side+'.cast')]:
        (root/dest).write_bytes((run/src).read_bytes())
