"""Ajusta un PRM de prefijos con etiquetas blandas MC, separando problemas."""
import argparse
import gzip
import hashlib
import json
import os
import random
from pathlib import Path
import uuid

import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from peft import LoraConfig, PeftModel, TaskType, get_peft_model

REV = '7ae557604adf67be50417f59c2c2f167def9a775'

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 last_checkpoint(out):
    saved=[]
    for checkpoint in Path(out).glob('checkpoint-*'):
        marker=json.loads((checkpoint/'complete.json').read_text(encoding='utf8'))
        required={'adapter_model.safetensors','adapter_config.json','optimizer.pt','rng.pt','state.json'}
        if set(marker['sha256'])!=required or any(digest(checkpoint/name)!=sha for name,sha in marker['sha256'].items()):
            raise ValueError(f'Checkpoint alterado: {checkpoint}')
        state=json.loads((checkpoint/'state.json').read_text(encoding='utf8'))
        if state['global_step']!=marker['global_step'] or checkpoint.name!=f"checkpoint-{state['global_step']}":
            raise ValueError(f'Estado de checkpoint incompatible: {checkpoint}')
        saved.append((state['global_step'],checkpoint,state))
    return max(saved,key=lambda x:x[0]) if saved else (0,None,None)

def save_checkpoint(out,model,opt,global_step,epoch,next_batch):
    out=Path(out);staging=out/('.staging-'+uuid.uuid4().hex);staging.mkdir()
    model.save_pretrained(staging)
    torch.save(opt.state_dict(),staging/'optimizer.pt')
    torch.save({'torch':torch.get_rng_state(),'cuda':torch.cuda.get_rng_state_all(),'python':random.getstate()},staging/'rng.pt')
    (staging/'state.json').write_text(json.dumps({'global_step':global_step,'epoch':epoch,'next_batch':next_batch},indent=2),encoding='utf8')
    required=['adapter_model.safetensors','adapter_config.json','optimizer.pt','rng.pt','state.json']
    marker={'global_step':global_step,'sha256':{name:digest(staging/name) for name in required}}
    (staging/'complete.json').write_text(json.dumps(marker,indent=2),encoding='utf8')
    target=out/f'checkpoint-{global_step}'
    if target.exists():raise FileExistsError(f'Checkpoint ya existe: {target}')
    os.replace(staging,target)
    return target

def main():
    ap=argparse.ArgumentParser()
    ap.add_argument('--labels',required=True)
    ap.add_argument('--samples',required=True,help='El mismo JSONL comprimido usado para generar')
    ap.add_argument('--model-path',required=True)
    ap.add_argument('--output',required=True)
    ap.add_argument('--batch',type=int,default=4)
    ap.add_argument('--epochs',type=int,default=1)
    ap.add_argument('--smoke',action='store_true',help='Prueba de instalación separada; no produce el adaptador de campaña')
    ap.add_argument('--resume',action='store_true',help='Reanuda el último checkpoint completo de esta campaña')
    args=ap.parse_args()
    if Path(args.model_path).name != REV or args.batch<1 or args.epochs<1: ap.error('Revisión, lote o épocas inválidos')
    if not torch.cuda.is_available(): raise RuntimeError('Se requiere CUDA')
    out=Path(args.output)
    if out.exists() and any(out.iterdir()) and not args.resume: raise ValueError('El directorio de salida debe estar vacío o se debe solicitar --resume')
    if (out/'training.json').exists(): raise ValueError('La campaña ya terminó')
    folder=Path(args.labels)
    protocol=json.loads((folder/'protocol.json').read_text(encoding='utf8'))
    count=protocol['problems']
    if protocol['rollouts']!=8 or (not args.smoke and count!=300) or (args.smoke and not 2<=count<300):
        raise ValueError('La campaña requiere 300 problemas; el smoke separado requiere de 2 a 299, siempre con ocho continuaciones')
    if hashlib.sha256(Path(args.samples).read_bytes()).hexdigest()!=protocol['samples_sha256']:
        raise ValueError('El corpus no coincide con el manifiesto')
    with gzip.open(args.samples,'rt',encoding='utf8') as f:
        samples=[json.loads(line) for line in f if line.strip()]
    chosen=[x for x in samples if x['problem']<count and x['sample']==0]
    if {x['problem'] for x in chosen}!=set(range(count)) or len(chosen)!=count:
        raise ValueError('Faltan soluciones de origen')
    originals={x['problem']:x for x in chosen}
    expected={(x['problem'],i) for x in chosen for i,line in enumerate([s for s in x['text'].splitlines() if s.strip()])}
    present={(int(p.name[1:5]),int(p.name[7:11])) for p in folder.glob('p*-s*.json')}
    if expected!=present: raise ValueError(f'Prefijos incompletos o extra: faltan {len(expected-present)}, sobran {len(present-expected)}')
    rows=[]; missing=0; unknown=0; labels_digest=hashlib.sha256()
    for file in sorted(folder.glob('p*-s*.json')):
        raw=file.read_bytes(); labels_digest.update(raw)
        row=json.loads(raw)
        if len(row['continuations'])!=8: raise ValueError('Prefijo incompleto')
        origin=originals[row['problem']]
        lines=[s for s in origin['text'].splitlines() if s.strip()]
        if row['question']!=origin['question'] or row['reference']!=origin['reference'] or row['prefix']!='\n'.join(lines[:row['step']+1]):
            raise ValueError('El prefijo no corresponde al corpus de origen')
        for continuation in row['continuations']:
            answer=continuation['answer']
            if continuation['correct']!=(None if answer is None else int(answer==row['reference'])):
                raise ValueError('Etiqueta inconsistente con respuesta extraída')
        known=[x['correct'] for x in row['continuations'] if x['correct'] is not None]
        unknown += 8-len(known)
        if not known:
            missing+=1
            continue
        rows.append({'problem':row['problem'],'step':row['step'],'question':row['question'],
                     'prefix':row['prefix'],'target':sum(known)/len(known),'weight':len(known)})
    if not rows or set(r['problem'] for r in rows)!=set(range(count)):
        raise ValueError('Faltan problemas en la campaña')
    split=270 if not args.smoke else max(1,int(.9*count))
    train=[r for r in rows if r['problem']<split]
    valid=[r for r in rows if split<=r['problem']<count]
    print('Prefijos',len(rows),'sin respuestas reconocidas',missing,'continuaciones sin extracción',unknown,flush=True)
    run_config={'revision':REV,'scope':'smoke' if args.smoke else 'full','problems':count,
                'labels_protocol_sha256':digest(folder/'protocol.json'),'labels_sha256':labels_digest.hexdigest(),
                'samples_sha256':digest(args.samples),'model_sha256':digest(Path(args.model_path)/'model.safetensors'),
                'code_sha256':digest(__file__),'batch':args.batch,'epochs':args.epochs,'seed':42,
                'checkpoint_frequency_batches':100,'truncation_side':'left','max_length':768}
    out.mkdir(parents=True,exist_ok=True);run_file=out/'run_config.json'
    if run_file.exists():
        if json.loads(run_file.read_text(encoding='utf8'))!=run_config:raise ValueError('Configuración de entrenamiento diferente')
    elif args.resume:raise ValueError('No hay configuración previa para reanudar')
    else:run_file.write_text(json.dumps(run_config,indent=2,ensure_ascii=False),encoding='utf8')
    _,checkpoint,resume_state=last_checkpoint(out)
    if args.resume and checkpoint is None:
        print('No hay checkpoint completo: se reinicia desde la base y se conserva cualquier temporal.',flush=True)
    if not args.resume and checkpoint:raise ValueError('Hay checkpoints previos; usa --resume')
    torch.manual_seed(42); random.seed(42)
    tok=AutoTokenizer.from_pretrained(args.model_path,local_files_only=True)
    tok.pad_token=tok.eos_token
    # La última representación debe corresponder al final del prefijo, no a
    # un token anterior elegido al recortar por la derecha.
    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
    base.config.use_cache=False
    config=LoraConfig(task_type=TaskType.SEQ_CLS,r=8,lora_alpha=16,lora_dropout=.05,
                      target_modules=['q_proj','v_proj'],modules_to_save=['score'])
    model=(PeftModel.from_pretrained(base,checkpoint,is_trainable=True) if checkpoint else get_peft_model(base,config)).to('cuda')
    truncation={'train':0,'valid':0,'phase':'train'}
    def collate(batch):
        text=['Question: '+r['question']+'\nSolution: '+r['prefix'] for r in batch]
        original=tok(text,padding=False,truncation=False)
        truncation[truncation['phase']]+=sum(len(ids)>768 for ids in original['input_ids'])
        enc=tok(text,padding=True,truncation=True,max_length=768,return_tensors='pt')
        return enc,torch.tensor([r['target'] for r in batch]),torch.tensor([r['weight'] for r in batch])
    opt=torch.optim.AdamW((p for p in model.parameters() if p.requires_grad),lr=2e-4)
    global_step=resume_state['global_step'] if resume_state else 0
    if checkpoint:
        opt.load_state_dict(torch.load(checkpoint/'optimizer.pt',map_location='cuda',weights_only=False))
        rng=torch.load(checkpoint/'rng.pt',map_location='cpu',weights_only=False)
        torch.set_rng_state(rng['torch']);torch.cuda.set_rng_state_all(rng['cuda']);random.setstate(rng['python'])
    for epoch in range(args.epochs):
        if resume_state and epoch<resume_state['epoch']:continue
        generator=torch.Generator().manual_seed(42+epoch)
        loader=DataLoader(train,batch_size=args.batch,shuffle=True,collate_fn=collate,generator=generator)
        model.train()
        for step,(inputs,targets,weights) in enumerate(loader):
            if resume_state and epoch==resume_state['epoch'] and step<resume_state['next_batch']:continue
            inputs={k:v.to('cuda') for k,v in inputs.items()}
            targets=targets.to('cuda'); weights=weights.to('cuda')
            opt.zero_grad(set_to_none=True)
            logits=model(**inputs).logits.squeeze(-1).float()
            loss=(F.binary_cross_entropy_with_logits(logits,targets,reduction='none')*weights).sum()/weights.sum()
            if not torch.isfinite(loss): raise ValueError('Pérdida no finita')
            loss.backward(); opt.step();global_step+=1
            if step%100==0: print('época',epoch,'lote',step,'pérdida',float(loss.detach()),flush=True)
            if global_step%100==0 or step+1==len(loader):save_checkpoint(out,model,opt,global_step,epoch,step+1)
    model.eval(); weighted_loss=0.; total=0;truncation['phase']='valid';bins=[{'n':0,'predicted':0.,'observed':0.} for _ in range(10)]
    with torch.inference_mode():
        for inputs,targets,weights in DataLoader(valid,batch_size=args.batch,collate_fn=collate):
            inputs={k:v.to('cuda') for k,v in inputs.items()}
            logits=model(**inputs).logits.squeeze(-1).float().cpu()
            weighted_loss+=float((F.binary_cross_entropy_with_logits(logits,targets,reduction='none')*weights).sum())
            total+=int(weights.sum())
            for predicted,target,weight in zip(torch.sigmoid(logits).tolist(),targets.tolist(),weights.tolist()):
                slot=bins[min(9,int(10*predicted))];slot['n']+=int(weight)
                slot['predicted']+=predicted*weight;slot['observed']+=target*weight
    for slot in bins:
        if slot['n']:
            slot['predicted']/=slot['n'];slot['observed']/=slot['n']
    out.mkdir(parents=True,exist_ok=True)
    model.save_pretrained(out); tok.save_pretrained(out)
    manifest={'revision':REV,'scope':'smoke' if args.smoke else 'full',
              'training_problems':[0,split-1],'validation_problems':[split,count-1],
              'train_prefixes':len(train),'valid_prefixes':len(valid),'unknown_rollouts':unknown,
              'all_unknown_prefixes':missing,'validation_bce':weighted_loss/total,
              'validation_calibration_bins':bins,
              'batch':args.batch,'epochs':args.epochs,'seed':42,'truncation_side':'left',
              'truncated_train_encodings':truncation['train'],'truncated_valid_encodings':truncation['valid'],
              'code_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
              'model_sha256':digest(Path(args.model_path)/'model.safetensors'),
              'torch':torch.__version__,
              'labels_protocol_sha256':hashlib.sha256((folder/'protocol.json').read_bytes()).hexdigest(),
              'labels_sha256':labels_digest.hexdigest(),
              'adapter_sha256':hashlib.sha256((out/'adapter_model.safetensors').read_bytes()).hexdigest()}
    (out/'training.json').write_text(json.dumps(manifest,indent=2,ensure_ascii=False),encoding='utf8')
    print(json.dumps(manifest,ensure_ascii=False,indent=2),flush=True)

if __name__=='__main__': main()
