"""Tres rondas STaR con muestras y adaptadores reanudables, GSM8K y LoRA."""
import argparse
import gzip
import hashlib
import json
import os
import random
import time
import uuid
from collections import Counter
from pathlib import Path

import torch
from torch.utils.data import DataLoader
from transformers import AutoModelForCausalLM,AutoTokenizer
from peft import LoraConfig,TaskType,get_peft_model,PeftModel
import answer_extract_v2 as extractor
import train_generate_fast as extractor_helper

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 training_checkpoint(folder):
    found=[]
    for path in Path(folder).glob('checkpoint-*'):
        marker=json.loads((path/'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(path/n)!=h for n,h in marker['sha256'].items()):
            raise ValueError(f'Checkpoint alterado: {path}')
        state=json.loads((path/'state.json').read_text(encoding='utf8'))
        if state['step']!=marker['step'] or path.name!=f"checkpoint-{state['step']}":raise ValueError('Paso incompatible')
        found.append((state['step'],path,state))
    return max(found,key=lambda x:x[0]) if found else (0,None,None)

def save_training_checkpoint(folder,model,optimizer,step,elapsed):
    folder=Path(folder);staging=folder/('.staging-'+uuid.uuid4().hex);staging.mkdir()
    model.save_pretrained(staging);torch.save(optimizer.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')
    save_json(staging/'state.json',{'step':step,'elapsed_seconds':elapsed})
    required=['adapter_model.safetensors','adapter_config.json','optimizer.pt','rng.pt','state.json']
    save_json(staging/'complete.json',{'step':step,'sha256':{name:digest(staging/name) for name in required}})
    target=folder/f'checkpoint-{step}'
    if target.exists():raise FileExistsError(target)
    os.replace(staging,target)
    return target

def prompt(question,answer=None):
    base='Solve step by step. '+question+'\nGive the final numerical answer on its own line as #### followed by the number.'
    return base if answer is None else base+'\nThe correct answer is '+answer+'. Explain how to obtain it.'

def load_model(model_path,adapter=None):
    base=AutoModelForCausalLM.from_pretrained(model_path,dtype=torch.bfloat16,local_files_only=True)
    return (PeftModel.from_pretrained(base,adapter) if adapter else base).to('cuda').eval()

def sample_group(model,tok,question,reference,seed,n=8,rational=False):
    message=prompt(question,reference if rational else None)
    encoded=tok.apply_chat_template([{'role':'user','content':message}],add_generation_prompt=True,
                                    tokenize=True,return_tensors='pt',return_dict=True).to('cuda')
    ids=encoded['input_ids'].repeat(n,1);mask=encoded['attention_mask'].repeat(n,1)
    torch.manual_seed(seed)
    torch.cuda.synchronize();started=time.perf_counter()
    with torch.inference_mode():
        output=model.generate(input_ids=ids,attention_mask=mask,do_sample=True,temperature=.8,top_p=.9,
                              top_k=0,repetition_penalty=1.1,max_new_tokens=256,pad_token_id=tok.eos_token_id)
    torch.cuda.synchronize();elapsed=time.perf_counter()-started
    results=[]
    eos=model.generation_config.eos_token_id
    eos_ids=set(eos if isinstance(eos,list) else [eos]) | {tok.eos_token_id}
    for seq in output:
        tokens=seq[ids.shape[1]:].tolist()
        stop=next((i for i,t in enumerate(tokens) if t in eos_ids),None)
        if stop is not None:tokens=tokens[:stop+1]
        text=tok.decode(tokens,skip_special_tokens=True)
        truncated=stop is None and len(tokens)>=256
        answer=extractor.extract(text,truncated=truncated)
        results.append({'text':text,'answer':answer,'correct':None if answer is None else int(answer==reference),
                        'tokens_in':int(encoded['attention_mask'].sum()),'tokens_out':len(tokens),'truncated':truncated})
    return results,elapsed

def save_json(path,payload):
    tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(payload,ensure_ascii=False),encoding='utf8');tmp.replace(path)

def generate(model,tok,rows,folder,round_id,split):
    folder.mkdir(parents=True,exist_ok=True)
    for i,row in enumerate(rows):
        target=folder/f'{split}-{round_id}-{i:04d}.json'
        if target.exists():
            saved=json.loads(target.read_text(encoding='utf8'))
            if saved['problem']!=i or saved['question']!=row['question'] or saved['reference']!=row['reference'] or len(saved['samples'])!=8:
                raise ValueError('Checkpoint de generación incompatible')
            continue
        seed=1000000+round_id*10000+i+(500000 if split=='test' else 0)
        answers,elapsed=sample_group(model,tok,row['question'],row['reference'],seed)
        rational=[];rational_elapsed=0.
        if split=='train' and not any(x['correct']==1 for x in answers):
            rational,rational_elapsed=sample_group(model,tok,row['question'],row['reference'],seed+4000000,n=1,rational=True)
        save_json(target,{'problem':i,'question':row['question'],'reference':row['reference'],
                          'samples':answers,'rationalizations':rational,'generation_seconds':elapsed,
                          'rationalization_seconds':rational_elapsed})
        if i%20==0:print(split,'ronda',round_id,'problema',i,'de',len(rows),flush=True)

def build_dataset(folder,round_id,count):
    result=[]
    for i in range(count):
        row=json.loads((folder/f'train-{round_id}-{i:04d}.json').read_text(encoding='utf8'))
        seen=set()
        for entry in row['samples']+row['rationalizations']:
            key=' '.join(entry['text'].lower().split())
            if entry['correct']!=1 or key in seen:continue
            seen.add(key)
            result.append({'problem':i,'question':row['question'],'text':entry['text']})
            if len(seen)==2:break
    return result

def train(model_path,tok,examples,out,seed=42,format_prompt=prompt):
    if not examples:raise ValueError('No hay muestras aceptadas: no se puede entrenar esta ronda')
    out=Path(out);out.mkdir(parents=True,exist_ok=True)
    examples_sha=hashlib.sha256(json.dumps(examples,sort_keys=True,ensure_ascii=False).encode('utf8')).hexdigest()
    rendered_sha=hashlib.sha256(json.dumps([format_prompt(x['question']) for x in examples],ensure_ascii=False).encode('utf8')).hexdigest()
    contract={'model_sha256':digest(Path(model_path)/'model.safetensors'),'code_sha256':digest(__file__),
              'examples_sha256':examples_sha,'prompts_sha256':rendered_sha,'seed':seed,'batch':4,'lr':2e-4,
              'max_length':768,'checkpoint_batches':25}
    contract_file=out/'run_config.json'
    if contract_file.exists():
        if json.loads(contract_file.read_text(encoding='utf8'))!=contract:raise ValueError('Configuración de entrenamiento diferente')
    elif any(out.iterdir()):raise ValueError('Directorio previo sin configuración')
    else:save_json(contract_file,contract)
    resume_step,checkpoint,state=training_checkpoint(out)
    torch.manual_seed(seed);random.seed(seed);tok.padding_side='right'
    base=AutoModelForCausalLM.from_pretrained(model_path,dtype=torch.bfloat16,local_files_only=True)
    base.config.use_cache=False
    model=(PeftModel.from_pretrained(base,checkpoint,is_trainable=True) if checkpoint else
           get_peft_model(base,LoraConfig(task_type=TaskType.CAUSAL_LM,r=8,lora_alpha=16,lora_dropout=.05,
                                         target_modules=['q_proj','v_proj']))).to('cuda').train()
    def collate(batch):
        inputs=[];labels=[]
        for row in batch:
            user={'role':'user','content':format_prompt(row['question'])}
            prefix=tok.apply_chat_template([user],add_generation_prompt=True,tokenize=True,return_dict=False)
            full=tok.apply_chat_template([user,{'role':'assistant','content':row['text']}],tokenize=True,return_dict=False)
            if full[:len(prefix)]!=prefix:raise ValueError('La plantilla no conserva el prefijo de usuario')
            if len(full)>768:raise ValueError('Texto demasiado largo para esta configuración; registra y ajusta el protocolo')
            inputs.append(full);labels.append([-100]*len(prefix)+full[len(prefix):])
        length=max(map(len,inputs))
        pad=tok.pad_token_id
        return {'input_ids':torch.tensor([x+[pad]*(length-len(x)) for x in inputs],device='cuda'),
                'attention_mask':torch.tensor([[1]*len(x)+[0]*(length-len(x)) for x in inputs],device='cuda'),
                'labels':torch.tensor([x+[-100]*(length-len(x)) for x in labels],device='cuda')}
    loader=DataLoader(examples,batch_size=4,shuffle=True,collate_fn=collate,
                      generator=torch.Generator().manual_seed(seed))
    optimizer=torch.optim.AdamW((p for p in model.parameters() if p.requires_grad),lr=2e-4)
    if checkpoint:
        optimizer.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'])
    started=time.perf_counter()
    for step,batch in enumerate(loader):
        if step<resume_step:continue
        optimizer.zero_grad(set_to_none=True);loss=model(**batch).loss
        if not torch.isfinite(loss):raise ValueError('Pérdida no finita')
        loss.backward();optimizer.step()
        if step%25==0:print('entrenamiento lote',step,'pérdida',float(loss.detach()),flush=True)
        if (step+1)%25==0 or step+1==len(loader):
            save_training_checkpoint(out,model,optimizer,step+1,(state['elapsed_seconds'] if state else 0.)+time.perf_counter()-started)
    model.save_pretrained(out);tok.save_pretrained(out)
    elapsed=(state['elapsed_seconds'] if state else 0.)+time.perf_counter()-started
    meta={'examples':len(examples),'seconds':elapsed,'seed':seed,
          'adapter_sha256':digest(out/'adapter_model.safetensors')}
    save_json(out/'completed.json',meta)
    print('adaptador completo',out,'ejemplos',len(examples),'segundos',elapsed,flush=True)
    del model,base
    torch.cuda.empty_cache()

def summarize(folder,round_id,test_count):
    rows=[json.loads((folder/f'test-{round_id}-{i:04d}.json').read_text(encoding='utf8')) for i in range(test_count)]
    p1=[];p8=[];unknown=0
    for row in rows:
        answers=row['samples'];unknown+=sum(a['correct'] is None for a in answers)
        correct=sum(a['correct']==1 for a in answers)
        p1.append(correct/8);p8.append(int(correct>0))
    rng=random.Random(73)
    result={}
    for name,values in [('pass1',p1),('pass8',p8)]:
        boots=sorted(sum(rng.choice(values) for _ in values)/len(values) for _ in range(2000))
        result[name]={'mean':sum(values)/len(values),'bootstrap_95':[boots[49],boots[1949]]}
    result['unknown']=unknown
    save_json(folder/f'summary-{round_id}.json',result)
    print('ronda',round_id,json.dumps(result),flush=True)

def main():
    ap=argparse.ArgumentParser()
    ap.add_argument('--model-path',required=True);ap.add_argument('--train-records',required=True)
    ap.add_argument('--test-samples',required=True);ap.add_argument('--output',required=True)
    ap.add_argument('--train-count',type=int,default=300);ap.add_argument('--test-count',type=int,default=200)
    args=ap.parse_args();base=Path(args.model_path)
    if base.name!=REV or not 1<=args.train_count<=300 or not 1<=args.test_count<=200:ap.error('Revisión o número incorrecto')
    if not torch.cuda.is_available():raise RuntimeError('Se requiere CUDA')
    training=json.loads(Path(args.train_records).read_text(encoding='utf8'))[:args.train_count]
    training=[{'question':r['question'],'reference':extractor.extract(r['answer'])} for r in training]
    if any(r['reference'] is None for r in training):raise ValueError('Referencia no extraída')
    with gzip.open(args.test_samples,'rt',encoding='utf8') as f:rows=[json.loads(s) for s in f if s.strip()]
    test=[{'question':r['pregunta'],'reference':r['referencia']} for r in rows if r['problema']<args.test_count and r['muestra']==0]
    if len(test)!=args.test_count:raise ValueError('Problemas de prueba incompletos')
    out=Path(args.output);out.mkdir(parents=True,exist_ok=True)
    protocol={'revision':REV,'model_sha256':digest(base/'model.safetensors'),
              'train_sha256':digest(args.train_records),'test_sha256':digest(args.test_samples),
              'train_count':args.train_count,'test_count':args.test_count,'rounds':3,'samples':8,
              'seed_rule':'1000000 + round*10000 + problem + test*500000',
              'temperature':.8,'top_p':.9,'repetition_penalty':1.1,'max_new_tokens':256,
              'torch':torch.__version__,'gpu':torch.cuda.get_device_name(),
              'code_sha256':digest(__file__),'extractor_sha256':digest(extractor.__file__),
              'extractor_helper_sha256':digest(extractor_helper.__file__)}
    meta=out/'protocol.json'
    if meta.exists() and json.loads(meta.read_text(encoding='utf8'))!=protocol:raise ValueError('Protocolo diferente')
    if not meta.exists():save_json(meta,protocol)
    tok=AutoTokenizer.from_pretrained(base,local_files_only=True);tok.pad_token=tok.eos_token;tok.padding_side='left'
    for round_id in range(4):
        adapter=out/f'adapter-{round_id}' if round_id else None
        if adapter:
            complete=json.loads((adapter/'completed.json').read_text(encoding='utf8'))
            if digest(adapter/'adapter_model.safetensors')!=complete['adapter_sha256']:raise ValueError('Adaptador alterado')
        model=load_model(base,adapter)
        generate(model,tok,test,out,round_id,'test');summarize(out,round_id,args.test_count)
        if round_id<3:generate(model,tok,training,out,round_id,'train')
        del model;torch.cuda.empty_cache()
        if round_id<3:
            examples=build_dataset(out,round_id,args.train_count)
            save_json(out/f'training-{round_id}.json',examples)
            next_adapter=out/f'adapter-{round_id+1}'
            if not (next_adapter/'completed.json').exists():train(base,tok,examples,next_adapter,seed=42+round_id)
            tok.padding_side='left'

if __name__=='__main__':main()
