"""Replay immutable decisions and bodies, not model or engine inference."""
import copy
import gzip
import hashlib
import itertools
import json
from pathlib import Path
import sys

sys.path.insert(0, '/workspace/contextra-analytics-runtime-lifecycle-refactor')
from app.fight_r5.display import DisplayHold
from app.fight_r5.notification import NotificationState

base = Path('/data/codex-artifacts/contextra/action-model-eval/2026')
features = base/'2026-10-29_contextra-fight-b-refine_r01/Contextra_Fight_B_Review_20261029/01_camera24_fight/data/features.jsonl.gz'
diagnostic = base/'2026-10-30_contextra-r5-review-12clips_r01/Contextra_Fight_R5_Review_20261030/01_camera24_fight/data/R5_diagnostics.jsonl'
holds = {v: DisplayHold() for v in (0, 1, 3, 5)}
notifications = {v: NotificationState() for v in holds}
last_event = {v: None for v in holds}
events = {v: [] for v in holds}
rows = []
with gzip.open(features, 'rt') as ff, diagnostic.open() as df:
    for f, d in itertools.zip_longest(ff, df):
        assert f is not None and d is not None
        f, d = json.loads(f), json.loads(d)
        assert all(f[k] == d[k] for k in ('sample', 'source_frame', 'seconds'))
        before = copy.deepcopy((f, d))
        current = sorted({i for p in d['pairs'] if p['hit'] for i in p['orders']})
        assert bool(current) == d['hit']
        result = dict(frame=d['source_frame'], seconds=d['seconds'], hit=d['hit'], current=current)
        for seconds, hold in holds.items():
            visible = hold.step(d['seconds'], f['bodies'], current, seconds)
            assert set(current) <= set(visible) <= {b['order'] for b in f['bodies']}
            assert all(h['age_seconds'] <= seconds for h in hold.status['held'])
            n = notifications[seconds]
            if n.observe(d['seconds'], d['hit']):
                if last_event[seconds] is None or d['seconds'] - last_event[seconds] >= 10:
                    last_event[seconds] = d['seconds']
                    n.admitted(d['seconds']); events[seconds].append(d['source_frame'])
                else:
                    n.denied()
            result[str(seconds)] = visible
        assert (f, d) == before
        rows.append(result)
assert all(e == events[0] for e in events.values())
out = Path(__file__).parent
(out/'saved-display-replay.json').write_text(json.dumps(dict(
    input='01_camera24_fight', observations=len(rows), current_hits=sum(r['hit'] for r in rows),
    display_observations={s:sum(bool(r[str(s)]) for r in rows) for s in holds},
    unchanged_mock_event_frames=events[0],
    notification_clock='PTS simulation; not live wall-clock throughput',
    feature_sha256=hashlib.sha256(features.read_bytes()).hexdigest(),
    diagnostic_sha256=hashlib.sha256(diagnostic.read_bytes()).hexdigest(),
    result='PASS', rows=rows), indent=2))
print(json.dumps(dict(observations=len(rows), hits=sum(r['hit'] for r in rows),
    display={s:sum(bool(r[str(s)]) for r in rows) for s in holds}, events=events[0])))
