"""Convert reviewed prior evidence, never a final UTG, to the Native stream contract."""
import argparse, hashlib, json, math
from pathlib import Path

ROOT=Path(__file__).resolve().parents[1]
p=argparse.ArgumentParser();p.add_argument('--study',type=Path,required=True);a=p.parse_args()
source=a.study.resolve(); dest=ROOT/'analysis'; (dest/'events').mkdir(exist_ok=True)
manifest={}
def load(path):
    data=path.read_bytes();manifest[str(path)]=hashlib.sha256(data).hexdigest();return data
entries=json.loads(load(source/'analysis/entry-groups.json'));catalog=[];runs=[]
for path in sorted((source/'analysis/traces').glob('*.jsonl')):
    rows=[json.loads(line) for line in load(path).splitlines()];rid=path.stem;run_id=rows[0]['run_id'];out=[]
    for i,e in enumerate(rows):
        assert e['order']==i and e['raw_event']['input_confirmed'] is True
        progress=e.get('latest_selection')
        if progress and progress['monotonic_ns']>e['monotonic_ns']:raise ValueError('future source selection')
        out.append(dict(schema=1,run_id=run_id,event_seq=i+1,event_kind='TRANSITION',timestamp=e['wall_time_ms'],
            monotonic_ns=e['monotonic_ns'],source_state=e['state'],target_state=e['target_state'],
            source_activity=e['source_activity'],target_activity=e['target_activity'],action_type=e['action_type'],
            model_action_identity=e['model_action'],transition_identity=e['transition_id'],
            native_transition_identity=e['raw_event'].get('native_edge_id'),input_id=e['input_path'],
            execution_confirmed=True,is_back=e['action_type']=='MODEL_BACK',is_restart=None,
            native_new_state=e['new_state'],native_new_model_action=e['new_model_action'],
            is_new_state=e['first_observed_target_raw'],is_new_transition=e['first_model_transition_flow'],
            segment_id=e['segment'],gap_before=e['gap_before'],model_progress=progress,
            concrete_identity=e['identity_digest'],source_gui_id=e['source_gui_id'],target_gui_id=e['target_gui_id'],
            abstraction_version=e['version'],input_version=e['input_version'],
            archive_evidence=dict(native_event_line=e['event_line'],input_path=e['input_path'],receipt_path=e['receipt_path']),
            restart_certification='UNKNOWN; original gaps segment; no fabricated restart edges'))
    f=dest/'events'/(rid+'.jsonl');f.write_text(''.join(json.dumps(e,ensure_ascii=False,separators=(',',':'))+'\n' for e in out))
    runs.append(dict(run=rid,run_id=run_id,count=len(out),events=str(f.relative_to(ROOT)),checkpoints=sorted({math.floor(len(out)*q) for q in [.25,.5,.75,1]})))
    for g in entries:
        if g['run']!=rid:continue
        catalog.append(dict(group_id=rid+':'+g['id'],run_id=run_id,function=g['function'],category='I',
            status='exploratory',oracle=True,human_confirmed=False,source_activity=g['source_activity'],
            transition_ids=g['events'],provenance='Prior study frozen exploratory occurrence set; evaluation Oracle, not online labels'))
assert sum(r['count'] for r in runs)==23279
(dest/'runs.json').write_text(json.dumps(runs,indent=2));(dest/'entries-oracle.json').write_text(json.dumps(catalog,ensure_ascii=False))
(dest/'source-hashes.json').write_text(json.dumps(manifest,indent=2));print('PREPARED',len(runs),sum(r['count'] for r in runs),len(catalog))
