"""Read-only cache bridge. User anchors are reference annotations, never exact GT."""
import hashlib
import json
from pathlib import Path

OUT=Path('/out')
REMOTE_BASE='/storage/contextra/experiments/action-model-eval/2026'


def evidence(path):
    assert path.startswith(REMOTE_BASE+'/')
    return Path('/evidence')/path[len(REMOTE_BASE)+1:]


def load(clip):
    spec=json.loads((OUT/'specs.json').read_text())[clip]
    cache=evidence(spec['cache'])/'inputs'
    raw=(cache/'pose.json').read_bytes()
    assert hashlib.sha256(raw).hexdigest()==spec['cache_sha256']
    all_rows=json.loads(raw);chosen=set(spec['selected_samples'])
    assert len(chosen)==len(spec['selected_samples'])
    selected=[all_rows[i] for i in spec['selected_samples']]
    assert all(r['sample']==i for i,r in enumerate(all_rows))
    rows=[r for r in all_rows if selected[0]['seconds']-3-1e-8<=r['seconds']<=selected[-1]['seconds']+1e-8]
    assert all(b['seconds']>a['seconds'] and b['sample']>a['sample'] for a,b in zip(rows,rows[1:]))
    assert len([r for r in rows if r['sample'] in chosen])==len(chosen)
    maps={}
    if spec['domain']=='self':
        maps={int(r['sample']):r for r in json.loads((OUT/'self_maps.json').read_text())[clip]}
        assert len(maps)==len(chosen)
        for r in rows:
            m=maps[r['sample']]
            assert r['source_frame']==int(m['clip_frame_1based'])
            assert abs(r['seconds']-float(m['clip_pts_seconds']))<1e-5
    return rows,chosen,spec,cache,maps


def annotations(clip, rows, maps):
    cases=json.loads((OUT/'cases.json').read_text())['cases']
    out={}
    bounds={'01_camera24_fight':(242,723),'06_KISA_fight_C00_008_0005':(154,1792),
            '07_KISA_fight_C00_015_0009':(106,1576),'08_KISA_fight_C00_018_0012':(385,1741),
            '09_KISA_fight_C00_021_0011':(121,1573)}
    negatives=('02_','03_','04_','11_','12_','13_','14_','15_')
    for r in rows:
        tag='unknown';ids=[];key=clip+':'+str(r['source_frame']);review=None
        if clip.startswith('SELF_'):
            review=int(maps[r['sample']]['review_frame_1based']);key='SELF01:'+str(review)
            applicable=[c for c in cases if not c['single_anchor'] and
                        c['review_anchor_range'][0]<=review<=c['review_anchor_range'][1]]
            ids=[c['case_id'] for c in applicable]
            labels={c['fight_expectation'] for c in applicable}
            if labels=={'non_event'}:tag='negative_reference'
            elif labels=={'event_desired'}:tag='positive_reference'
            elif labels:tag='conflict_or_pending'
        elif clip in bounds and bounds[clip][0]<=r['source_frame']<=bounds[clip][1]:tag='positive_reference'
        elif clip.startswith(negatives):tag='negative_reference'
        out[r['sample']]=dict(reference=tag,case_ids=ids,dedupe_key=key,review_frame=review,
            precision='approximate user reference, NOT exact GT')
    return out
