"""Replay contrafactual de presupuestos comunes, sin nuevas llamadas al modelo."""
import hashlib
import json
from pathlib import Path
from statistics import mean
import sys

from analyze_mbpp import evaluation_library

# Rejilla fijada por escala de tokens antes de consultar resultados.
CAPS=(256,512,768,1024,1536,2048,3072,4096)
METHODS=('resample','binary','repair','reflexion')
if len(sys.argv)!=3:raise SystemExit('uso: replay_mbpp_budget.py mbpp-7b.jsonl salida.json')
source=Path(sys.argv[1])
data=source.read_bytes();lines=[json.loads(x) for x in data.splitlines()]
rows=lines[1:];groups={}
for row in rows:
    key=(row['task_id'],row['method'])
    if key in groups:raise ValueError('tarea duplicada')
    if row['method'] not in METHODS or row['rounds']!=2 or len(row['candidates'])!=3:
        raise ValueError('protocolo ajeno o sin tres candidatos')
    if len(row['reflections'])!=(2 if row['method']=='reflexion' else 0):
        raise ValueError('número de reflexiones inválido')
    groups[key]=row
ids=sorted({task for task,_ in groups})
assert len(ids)==50 and set(groups)=={(task,method) for task in ids for method in METHODS}

def replay(row,cap):
    events=[]
    for i,candidate in enumerate(row['candidates']):
        if i and row['method']=='reflexion':events.append(('reflection',i-1,row['reflections'][i-1]))
        events.append(('candidate',i,candidate))
    spent_input=spent_output=0;complete=[];reflections=0;stop='completed';partial_output=0
    for kind,index,event in events:
        usage=event['usage'];p=usage['prompt_tokens'];o=usage['completion_tokens']
        if type(p) is not int or type(o) is not int or p<0 or o<0:raise ValueError('uso inválido')
        remaining=cap-spent_input-spent_output
        if remaining<=p:
            stop='insufficient_input';break
        if remaining<p+o:
            spent_input+=p;partial_output=remaining-p;spent_output+=partial_output
            stop='partial_'+kind;break
        spent_input+=p;spent_output+=o
        if kind=='candidate':complete.append((index,event))
        else:reflections+=1
    selected=next(((i,c) for i,c in complete if c['visible_pass']),complete[-1] if complete else None)
    result={'task_id':row['task_id'],'completed_candidates':len(complete),'completed_reflections':reflections,
            'selected_index':selected[0] if selected else None,'abstain':selected is None,
            'success':bool(selected and selected[1]['visible_pass'] and selected[1]['hidden_pass']),
            'spent_input':spent_input,'spent_output':spent_output,'spent_total':spent_input+spent_output,
            'unused_budget':cap-spent_input-spent_output,'stop':stop,'partial_output_tokens':partial_output}
    assert result['spent_total']<=cap and result['unused_budget']>=0
    if stop=='completed':
        assert result['success']==row['success'] and result['selected_index']==row['selected_index']
        assert result['spent_total']==row['prompt_tokens']+row['completion_tokens']
    return result

evaluator=evaluation_library();result={
 'source_sha256':hashlib.sha256(data).hexdigest(),'n_tasks':len(ids),'r':2,'budget_grid':list(CAPS),
 'budget_unit':'tokens de entrada más salida por trayectoria',
 'rule':'Descartar la primera llamada incompleta; seleccionar el primer candidato completo que supera el test visible o, si ninguno, el último completo. Sin candidato: abstención y éxito operacional cero.',
 'limitation':'Replay contrafactual: supone que los prefijos medidos se mantendrían con un tope online; no se guardaron secuencias de tokens. Igual presupuesto disponible no implica igual gasto efectivo. Tests reservados públicos se usan solo para puntuar la selección.',
 'conditions':{},'comparisons':{},'traces':{}
}
for cap in CAPS:
    label=str(cap);records={m:[replay(groups[(i,m)],cap) for i in ids] for m in METHODS}
    result['traces'][label]=records;result['conditions'][label]={};result['comparisons'][label]={}
    base=records['resample'];baseline=[int(r['success']) for r in base]
    for offset,method in enumerate(METHODS):
        group=records[method];values=[int(r['success']) for r in group]
        stop_counts={name:sum(r['stop']==name for r in group) for name in sorted({r['stop'] for r in group})}
        result['conditions'][label][method]={
          'success':mean(values),'success_count':sum(values),'no_candidate':sum(r['abstain'] for r in group),
          'mean_completed_candidates':mean(r['completed_candidates'] for r in group),
          'mean_spent_input':mean(r['spent_input'] for r in group),
          'mean_spent_output':mean(r['spent_output'] for r in group),
          'mean_spent_total':mean(r['spent_total'] for r in group),'stop_counts':stop_counts}
        diffs=[a-b for a,b in zip(values,baseline)]
        interval=evaluator.paired_bootstrap([[x] for x in baseline],[[x] for x in values],n_boot=2000,seed=1414+cap+offset)
        result['comparisons'][label][method]={'difference_vs_resample':mean(diffs),'paired_bootstrap_95':list(interval)}
out=Path(sys.argv[2])
if out.exists():raise FileExistsError('no sobrescribir un replay existente')
out.write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf8')
print('Replay guardado:',out,'SHA256',hashlib.sha256(out.read_bytes()).hexdigest())
for cap in CAPS:
    print(cap,[(m,result['conditions'][str(cap)][m]['success_count'],
                result['conditions'][str(cap)][m]['mean_spent_total']) for m in METHODS])
