"""Auditoría independiente de una evaluación final bimanual LeRobot."""
import argparse
import hashlib
import json
import math
from pathlib import Path

p=argparse.ArgumentParser()
p.add_argument('result')
p.add_argument('--checkpoint',required=True)
p.add_argument('--task',required=True,choices=['transferencia','insercion'])
p.add_argument('--ensemble',action='store_true')
a=p.parse_args()
path=Path(a.result)
raw=path.read_bytes()
d=json.loads(raw)
c=d['contract']
with Path(a.checkpoint).open('rb') as f:
    checkpoint_hash=hashlib.file_digest(f,'sha256').hexdigest()
assert c['checkpoint_sha256']==checkpoint_hash and c['task']==a.task and c['ensemble']==a.ensemble
assert c['eval_seed']==20000 and c['episodes']==100 and c['max_steps'] is None
assert c['device_type']=='cpu' and c['lerobot']=='0.3.3'
records=d['records']
assert len(records)==100 and [r['seed'] for r in records]==list(range(20000,20100))
state_dim=len(records[0]['trace'][0]['state'])
assert state_dim>0 and (a.task!='transferencia' or state_dim==262)
for record in records:
    assert type(record['success']) is bool and record['steps']==len(record['trace'])==400
    for frame in record['trace']:
        assert len(frame['action'])==14 and len(frame['state'])==state_dim
        assert all(math.isfinite(x) for x in frame['action']+frame['state']+[frame['reward']])
    assert record['success']==any(frame['reward']==4.0 for frame in record['trace'])
    assert record['reward']==record['trace'][-1]['reward']
k=sum(r['success'] for r in records)
assert d['successes']==k and d['episodes']==100
n=100; z=1.96; den=1+z*z/n
center=(k/n+z*z/(2*n))/den
half=z*math.sqrt(k/n*(1-k/n)/n+z*z/(4*n*n))/den
interval=[max(0.,center-half),min(1.,center+half)]
assert all(abs(x-y)<1e-8 for x,y in zip(interval,d['wilson95']))
result={'scope':'100 episodios completos y sus trazas, no incertidumbre entre entrenamientos',
        'task':a.task,'ensemble':a.ensemble,'successes':k,'episodes':n,'wilson95':interval,
        'checkpoint_sha256':checkpoint_hash,'result_sha256':hashlib.sha256(raw).hexdigest(),
        'state_dimensions':state_dim,'action_dimensions':14,'steps_per_episode':400}
Path(str(path)+'.audit.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(result,ensure_ascii=False,indent=2))
