"""Independent comparison audit against unchanged raw cache and prior frame map."""
import csv
import hashlib
import json
import math
import os
from pathlib import Path

clip=os.environ['CLIP'];out=Path('/download')/clip/'data';prior=Path('/previous')/clip/'data'
check=json.loads((prior/'cache_validation.json').read_text())
raw=json.loads(Path('/cache/inputs/pose.json').read_text())
rows=[raw[i] for i in check['selected_samples']]
facts=[json.loads(s) for s in (out/'observation_states.jsonl').read_text().splitlines()]
maps=list(csv.DictReader((out/'frame_map.csv').open()))
oldmaps=list(csv.DictReader((prior/'frame_map.csv').open()))
assert len(rows)==len(facts)==len(maps)==len(oldmaps)==(650 if clip.startswith('06_') else 520)
assert json.loads((out/'input_rgb_sha256.json').read_text())==json.loads((prior/'input_rgb_sha256.json').read_text())
assert json.loads((out/'identity_palette.json').read_text())==json.loads((prior/'identity_palette.json').read_text())
edges=((5,6),(5,7),(7,9),(6,8),(8,10),(5,11),(6,12),(11,12),(11,13),(13,15),(12,14),(14,16))
counts={'baseline':0,'added':0,'empty_cache_frames':0,'no_visible_frames':0,'detail_omitted':0}
for r,f,m,om in zip(rows,facts,maps,oldmaps):
    assert (r['sample'],r['source_frame'],r['seconds'])==(f['sample'],f['source_frame'],f['seconds'])
    for k in ('output_frame','sample','source_frame','source_seconds','output_pts_seconds'):assert m[k]==om[k]
    assert len(r['persons'])==len(f['persons'])
    visible=[]
    for p,d in zip(r['persons'],f['persons']):
        assert p['track_id']==d['track_id'] and p['query']==d['query'] and p['bbox']==d['bbox'] and p['score']==d['person_score']
        assert d['joint_scores']==[x[2] for x in p['keypoints']]
        b=p['bbox'];s=p['score'];w,h=r['width'],r['height']
        valid=all(math.isfinite(x) for x in b+[s]) and 0<=s<=1 and b[0]<b[2] and b[1]<b[3] and b[2]>0 and b[3]>0 and b[0]<w and b[1]<h
        state='INVALID' if not valid else 'HIGH' if s>=.25 else 'LOW' if s>=.20 else 'BELOW'
        assert state==d['bbox_state'] and d['visible']==(state in ('HIGH','LOW'))
        expected=[]
        for x,y,score in p['keypoints']:
            ok=all(math.isfinite(v) for v in (x,y,score)) and 0<=x<=w and 0<=y<=h and 0<=score<=1
            expected.append('INVALID' if not ok else 'HIGH' if score>=.10 else 'LOW' if score>=.05 else 'BELOW')
        assert expected==d['joint_states']
        assert d['core_states']=={str(j):expected[j] for j in (5,6,11,12,7,8,9,10)}
        assert d['extra_states']=={str(j):expected[j] for j in (13,14,15,16)}
        for (a,b),edge in zip(edges,d['edge_states']):
            exp=None if expected[a] not in ('HIGH','LOW') or expected[b] not in ('HIGH','LOW') else 'HIGH' if expected[a]==expected[b]=='HIGH' else 'LOW'
            assert edge==exp
        if d['visible']:visible.append(d)
    assert [p['detail_slot'] for p in visible]==[i+1 if i<3 else None for i in range(len(visible))]
    assert len({tuple(p['identity_color']) for p in visible})==len(visible)
    hi=sum(p['bbox_state']=='HIGH' for p in visible);lo=len(visible)-hi
    assert int(m['baseline'])==hi and int(m['added'])==lo and int(m['visible'])==len(visible)
    counts['baseline']+=hi;counts['added']+=lo;counts['empty_cache_frames']+=not r['persons']
    counts['no_visible_frames']+=not visible;counts['detail_omitted']+=max(0,len(visible)-3)
    assert f['labels']['label_count']==len(visible) and f['labels']['label_overlap']==0 and f['labels']['label_joint_edge_overlap']==0
report=dict(status='PASS',frames=len(rows),raw_cache_equal=True,prior_rgb_hashes_equal=True,
    prior_frame_pts_equal=True,prior_real_id_palette_equal=True,counts=counts,
    score_and_coordinates_independent_check=True,semantic_accuracy_evaluated=False)
(out/'comparison_audit.json').write_text(json.dumps(report,indent=2));print(json.dumps(report))
