"""Puntúa prefijos de las candidatas de m23-l05 y compara reglas por problema."""
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

import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from peft import PeftModel

REV='7ae557604adf67be50417f59c2c2f167def9a775'
SOURCE_SHA='a16052484ad9b2ddc6aa9bb1d488c7e17719637f43a6e84de2b930b782c30f1a'

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

def main():
    ap=argparse.ArgumentParser()
    ap.add_argument('--scores',required=True,help='orm_test_scores.jsonl.gz de m23-l05')
    ap.add_argument('--adapter',required=True)
    ap.add_argument('--model-path',required=True)
    ap.add_argument('--output',required=True)
    ap.add_argument('--batch',type=int,default=8)
    args=ap.parse_args()
    if Path(args.model_path).name!=REV: ap.error('Se requiere la revisión 0.5B fijada')
    training=json.loads((Path(args.adapter)/'training.json').read_text(encoding='utf8'))
    if training.get('scope')!='full':raise ValueError('La evaluación completa exige el adaptador de la campaña, no un smoke')
    if training.get('model_sha256')!=digest(Path(args.model_path)/'model.safetensors'):
        raise ValueError('El modelo base no coincide con el usado para entrenar')
    adapter_hash=hashlib.sha256((Path(args.adapter)/'adapter_model.safetensors').read_bytes()).hexdigest()
    if adapter_hash!=training['adapter_sha256']: raise ValueError('Adaptador alterado')
    source_hash=hashlib.sha256(Path(args.scores).read_bytes()).hexdigest()
    if source_hash!=SOURCE_SHA: raise ValueError('No corresponde a las puntuaciones publicadas de m23-l05')
    out=Path(args.output); out.mkdir(parents=True,exist_ok=True)
    proto={'source_sha256':source_hash,'adapter_sha256':adapter_hash,'k':8,'batch':args.batch,'max_length':768,
           'truncation_side':'left','code_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
           'model_sha256':digest(Path(args.model_path)/'model.safetensors'),
           'torch':torch.__version__}
    meta=out/'protocol.json'
    if meta.exists() and json.loads(meta.read_text(encoding='utf8'))!=proto: raise ValueError('Protocolo distinto')
    if not meta.exists(): meta.write_text(json.dumps(proto,indent=2),encoding='utf8')
    with gzip.open(args.scores,'rt',encoding='utf8') as f:
        rows=[json.loads(line) for line in f if line.strip()]
    groups=defaultdict(list)
    for row in rows:
        if row['muestra']<8: groups[row['problema']].append(row)
    if set(groups)!=set(range(200)) or any(len(group)!=8 or {r['muestra'] for r in group}!=set(range(8)) for group in groups.values()):
        raise ValueError('Se necesitan ocho candidatas por cada uno de 200 problemas')
    tok=AutoTokenizer.from_pretrained(args.adapter,local_files_only=True); tok.pad_token=tok.eos_token
    tok.truncation_side='left'
    base=AutoModelForSequenceClassification.from_pretrained(args.model_path,num_labels=1,dtype=torch.bfloat16,local_files_only=True)
    base.config.pad_token_id=tok.pad_token_id
    model=PeftModel.from_pretrained(base,args.adapter).to('cuda').eval()
    all_scored=[]
    for problem in range(200):
        file=out/f'p{problem:04d}.json'
        if file.exists():
            scored=json.loads(file.read_text(encoding='utf8'))
            if len(scored)!=8 or {r['muestra'] for r in scored}!=set(range(8)): raise ValueError('Archivo incompleto o duplicado')
            source={r['muestra']:r for r in groups[problem]}
            if any(r['answer']!=source[r['muestra']]['respuesta'] or r['reference']!=source[r['muestra']]['referencia'] or
                   r['orm']!=source[r['muestra']]['score'] or not r['scores'] or
                   any(not math.isfinite(v) or not 0<=v<=1 for v in r['scores']) for r in scored):
                raise ValueError('Archivo previo incompatible con las candidatas originales')
        else:
            group=sorted(groups[problem],key=lambda r:r['muestra'])
            texts=[]; counts=[]
            for row in group:
                lines=[s for s in row['texto'].splitlines() if s.strip()]
                if not lines: raise ValueError('Solución sin pasos')
                counts.append(len(lines))
                texts.extend('Question: '+row['pregunta']+'\nSolution: '+'\n'.join(lines[:i+1]) for i in range(len(lines)))
            values=[]; token_counts=[]; truncations=[]
            with torch.inference_mode():
                for start in range(0,len(texts),args.batch):
                    original=tok(texts[start:start+args.batch],padding=False,truncation=False)
                    truncations.extend(len(ids)>768 for ids in original['input_ids'])
                    enc=tok(texts[start:start+args.batch],padding=True,truncation=True,max_length=768,return_tensors='pt').to('cuda')
                    token_counts.extend(enc['attention_mask'].sum(dim=1).cpu().tolist())
                    logits=model(**enc).logits.squeeze(-1).float()
                    if not torch.isfinite(logits).all(): raise ValueError('Puntuación no finita')
                    values.extend(torch.sigmoid(logits).cpu().tolist())
            scored=[]; idx=0
            for row,n in zip(group,counts):
                p=values[idx:idx+n]; cost=sum(token_counts[idx:idx+n]); truncated=sum(truncations[idx:idx+n]); idx+=n
                scored.append({'muestra':row['muestra'],'answer':row['respuesta'],'reference':row['referencia'],
                               'orm':row['score'],'scores':p,'tokens_prm':cost,'truncated_prefixes':truncated})
            temp=file.with_suffix('.tmp')
            temp.write_text(json.dumps(scored,ensure_ascii=False),encoding='utf8'); temp.replace(file)
            print('problema',problem,'prefijos',len(texts),'tokens evaluador',sum(token_counts),flush=True)
        all_scored.append(sorted(scored,key=lambda r:r['muestra']))
    names=['minimo','producto','ultimo','media','orm','voto','oraculo']
    def trial(group,k):
        group=group[:k]; result={}
        def score(row,method):
            p=row['scores']
            if method=='minimo': return min(p)
            if method=='producto': return sum(math.log(max(v,1e-30)) for v in p)
            if method=='ultimo': return p[-1]
            if method=='media': return mean(p)
            return row['orm']
        for method in names[:5]:
            row=max(group,key=lambda r:score(r,method))
            result[method]=int(row['answer'] is not None and row['answer']==row['reference'])
            result[method+'_sin_extraccion']=int(row['answer'] is None)
        # La falta de extracción no es una respuesta candidata en el voto.
        counts=Counter(r['answer'] for r in group if r['answer'] is not None)
        voted=max(counts,key=counts.get) if counts else None
        result['voto']=int(voted is not None and voted==group[0]['reference'])
        result['voto_sin_extraccion']=int(voted is None)
        result['oraculo']=int(any(r['answer'] is not None and r['answer']==r['reference'] for r in group))
        return result
    result={}
    for k in [1,2,4,8]:
        tasks=[trial(group,k) for group in all_scored]
        randomizer=random.Random(73)
        boot={name:[] for name in names}
        for _ in range(2000):
            sample=[randomizer.choice(tasks) for _ in tasks]
            for name in names: boot[name].append(mean(x[name] for x in sample))
        result[str(k)]={name:{'accuracy':mean(x[name] for x in tasks),
                             'bootstrap_95':[sorted(boot[name])[49],sorted(boot[name])[1949]],
                             'missing_fraction':None if name=='oraculo' else mean(x[name+'_sin_extraccion'] for x in tasks)}
                        for name in names}
    result['total_truncated_prefixes']=sum(row['truncated_prefixes'] for group in all_scored for row in group)
    (out/'summary.json').write_text(json.dumps(result,indent=2),encoding='utf8')
    print(json.dumps(result,indent=2),flush=True)

if __name__=='__main__': main()
