"""Reconstruye la selección PRM/ORM reservada desde los 200 grupos persistidos."""
import argparse
from collections import Counter,defaultdict
import gzip
import hashlib
import json
import math
from pathlib import Path
import random
from statistics import mean

SOURCE_SHA='a16052484ad9b2ddc6aa9bb1d488c7e17719637f43a6e84de2b930b782c30f1a'

def digest(path):
    h=hashlib.sha256()
    with Path(path).open('rb') as f:
        for b in iter(lambda:f.read(1024*1024),b''):h.update(b)
    return h.hexdigest()

def select(group,k):
    rows=group[:k]
    selectors={'minimo':lambda r:min(r['scores']),'producto':lambda r:sum(math.log(max(x,1e-30)) for x in r['scores']),
               'ultimo':lambda r:r['scores'][-1],'media':lambda r:mean(r['scores']),'orm':lambda r:r['orm']}
    result={}
    for key,score in selectors.items():
        chosen=max(rows,key=score);result[key]=int(chosen['answer'] is not None and chosen['answer']==chosen['reference'])
        result[key+'_sin_extraccion']=int(chosen['answer'] is None)
    votes=Counter(r['answer'] for r in rows if r['answer'] is not None)
    answer=max(votes,key=votes.get) if votes else None
    result['voto']=int(answer is not None and answer==rows[0]['reference'])
    result['voto_sin_extraccion']=int(answer is None)
    result['oraculo']=int(any(r['answer'] is not None and r['answer']==r['reference'] for r in rows))
    return result

def main():
    ap=argparse.ArgumentParser();ap.add_argument('--run',required=True);ap.add_argument('--scores',required=True)
    ap.add_argument('--adapter',required=True);ap.add_argument('--output',required=True);args=ap.parse_args()
    root=Path(args.run);source=Path(args.scores);adapter=Path(args.adapter)
    protocol=json.loads((root/'protocol.json').read_text(encoding='utf8'))
    training=json.loads((adapter/'training.json').read_text(encoding='utf8'))
    if (digest(source)!=SOURCE_SHA or protocol['source_sha256']!=SOURCE_SHA or
        training.get('scope')!='full' or digest(adapter/'adapter_model.safetensors')!=training['adapter_sha256'] or
        protocol['adapter_sha256']!=training['adapter_sha256'] or protocol['model_sha256']!=training['model_sha256'] or
        protocol['code_sha256']!=digest(Path(__file__).with_name('evaluate_prm.py')) or
        protocol['k']!=8 or protocol['max_length']!=768 or protocol['truncation_side']!='left'):
        raise ValueError('Protocolo o fuentes incompatibles')
    originals=defaultdict(dict)
    with gzip.open(source,'rt',encoding='utf8') as stream:
        for line in stream:
            row=json.loads(line)
            if row['muestra']<8:
                if row['muestra'] in originals[row['problema']]:raise ValueError('Candidata duplicada')
                originals[row['problema']][row['muestra']]=row
    if set(originals)!=set(range(200)) or any(set(x)!=set(range(8)) for x in originals.values()):
        raise ValueError('Candidatas de prueba incompletas')
    groups=[];hashes={};truncated=0
    for i in range(200):
        file=root/f'p{i:04d}.json';group=json.loads(file.read_text(encoding='utf8'))
        if len(group)!=8 or {r['muestra'] for r in group}!=set(range(8)):raise ValueError('Grupo incompleto')
        group.sort(key=lambda r:r['muestra'])
        for row in group:
            original=originals[i][row['muestra']]
            n=sum(bool(line.strip()) for line in original['texto'].splitlines())
            if (row['answer']!=original['respuesta'] or row['reference']!=original['referencia'] or
                row['orm']!=original['score'] or len(row['scores'])!=n or n==0 or
                any(not math.isfinite(x) or not 0<=x<=1 for x in row['scores']) or
                not isinstance(row['tokens_prm'],int) or row['tokens_prm']<n or
                not isinstance(row['truncated_prefixes'],int) or not 0<=row['truncated_prefixes']<=n):
                raise ValueError(f'Candidata incompatible: {file.name}')
            truncated+=row['truncated_prefixes']
        groups.append(group);hashes[file.name]=digest(file)
    names=['minimo','producto','ultimo','media','orm','voto','oraculo'];recalculated={}
    for k in (1,2,4,8):
        tasks=[select(group,k) for group in groups];rng=random.Random(73);boots={name:[] for name in names}
        for _ in range(2000):
            sampled=[rng.choice(tasks) for _ in tasks]
            for name in names:boots[name].append(mean(row[name] for row in sampled))
        recalculated[str(k)]={name:{'accuracy':mean(row[name] for row in tasks),
                                   'bootstrap_95':[sorted(boots[name])[49],sorted(boots[name])[1949]],
                                   'missing_fraction':None if name=='oraculo' else mean(row[name+'_sin_extraccion'] for row in tasks)}
                              for name in names}
    recalculated['total_truncated_prefixes']=truncated
    if json.loads((root/'summary.json').read_text(encoding='utf8'))!=recalculated:
        raise ValueError('Resumen o bootstrap no se reconstruyen')
    report={'scope':'Auditoría de selección por problema; no verifica corrección de cada paso.',
            'problems':200,'candidates':1600,'protocol_sha256':digest(root/'protocol.json'),
            'summary_sha256':digest(root/'summary.json'),'source_sha256':digest(source),
            'training_manifest_sha256':digest(adapter/'training.json'),'adapter_sha256':training['adapter_sha256'],
            'auditor_sha256':digest(__file__),'group_sha256':hashes}
    out=Path(args.output);out.parent.mkdir(parents=True,exist_ok=True)
    out.write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf8')
    print('Selección auditada: 200 problemas, 1600 candidatas y cuatro tamaños')

if __name__=='__main__':main()
