"""Resumen del agente; los tests del verificador comparten escenas y no son independientes."""
import argparse,json,math
from collections import Counter
from pathlib import Path
from statistics import NormalDist

def wilson(k,n):
 z=NormalDist().inv_cdf(.975);p=k/n;den=1+z*z/n;mid=(p+z*z/(2*n))/den;half=z*math.sqrt(p*(1-p)/n+z*z/(4*n*n))/den
 return [max(0.,mid-half),min(1.,mid+half)]
def analyze(data,expected):
 rows=data['records'];threshold=data.get('contract',{}).get('physical_success_coverage',.95);groups={}
 for r in rows:groups.setdefault(r['instruction'],[]).append(r)
 if len(groups)!=2 or any(len(v)!=expected for v in groups.values()):raise ValueError('Número de instrucciones o episodios incompleto')
 values=list(groups.values());seedsets=[set(r['seed'] for r in group) for group in values]
 if seedsets[0]!=seedsets[1] or len(seedsets[0])!=expected:raise ValueError('Escenas no emparejadas')
 summary=[];confusion=Counter();steps=[]
 for instruction,group in groups.items():
  for r in group:
   positives=[c for c in r['checks'] if c['vlm'] is True]
   verified=bool(len(positives)==2 and r['plan']==r['expected'] and all(c['oracle_for_evaluation'] for c in positives))
   if bool(r['success'])!=verified:raise ValueError('Éxito incoherente con plan y verificador')
   steps.append(r.get('steps',0))
   for c in r['checks']:
    if 'coverage_for_evaluation' in c and not (0<=c['coverage_for_evaluation']<=1 and bool(c['oracle_for_evaluation'])==(c['coverage_for_evaluation']>=threshold)):raise ValueError('Cobertura incoherente con umbral')
    if c['vlm'] is not None:confusion[('positive' if c['oracle_for_evaluation'] else 'negative')+'_'+('yes' if c['vlm'] else 'no')]+=1
  successes=sum(r['success'] for r in group)
  summary.append({'instruction':instruction,'episodes':len(group),'successes':successes,'wilson95':wilson(successes,len(group)),
                  'distinct_plans':list({json.dumps(r['plan'],ensure_ascii=False) for r in group}),
                  'correct_plan':sum(r['plan']==r['expected'] for r in group)})
 first={r['seed']:bool(r['success']) for r in values[0]};second={r['seed']:bool(r['success']) for r in values[1]}
 b=sum(first[s] and not second[s] for s in first);c=sum(second[s] and not first[s] for s in first);n=b+c
 p=1. if n==0 else min(1.,2*sum(math.comb(n,i) for i in range(min(b,c)+1))/2**n)
 return {'instructions':summary,'verifier_confusion':dict(confusion),'total_verifier_calls':sum(confusion.values()),
         'mean_steps':sum(steps)/len(steps),'paired_discordances':[b,c],'paired_exact_p':p,
         'limits':'Las consultas comparten escenas y el plan se genera una vez por instrucción; intervalos por episodio suponen independencia entre escenas y no recogen variación de entrenamiento.'}
if __name__=='__main__':
 parser=argparse.ArgumentParser();parser.add_argument('input');parser.add_argument('output');parser.add_argument('--episodes',type=int,default=50);args=parser.parse_args()
 result=analyze(json.loads(Path(args.input).read_text(encoding='utf8')),args.episodes)
 Path(args.output).write_text(json.dumps(result,indent=2,ensure_ascii=False),encoding='utf8');print(json.dumps(result,ensure_ascii=False))
