"""Potencial TFN pequeño con e3nn; requiere potenciales.py de la lección anterior."""
import argparse
import json
import os
import shutil
import subprocess
import time
import sys
from pathlib import Path
import numpy as np
import torch
from torch import nn
from e3nn import o3
try:
    from potenciales import load_data,values,predict,evaluate,Checkpoint,gpu_start,gpu_stop,save_json
except ModuleNotFoundError:
    sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'l24'))
    from potenciales import load_data,values,predict,evaluate,Checkpoint,gpu_start,gpu_stop,save_json


class SmallTensorPotential(nn.Module):
    def __init__(self,lmax=2,width=4,layers=2,cutoff=5.):
        super().__init__();self.lmax=lmax;self.width=width;self.cutoff=cutoff
        self.irreps=o3.Irreps(' + '.join(f'{width}x{l}{"e" if l%2==0 else "o"}' for l in range(lmax+1)))
        self.sh=o3.Irreps.spherical_harmonics(lmax)
        self.embed=nn.Embedding(100,width);self.register_buffer('centers',torch.linspace(0,cutoff,16))
        self.tp=nn.ModuleList([o3.FullyConnectedTensorProduct(self.irreps,self.sh,self.irreps,shared_weights=False) for _ in range(layers)])
        self.radial=nn.ModuleList([nn.Sequential(nn.Linear(16,32),nn.SiLU(),nn.Linear(32,t.weight_numel)) for t in self.tp])
        self.head=nn.Sequential(nn.Linear(width,32),nn.SiLU(),nn.Linear(32,1))

    def forward(self,z,pos):
        B,N,_=pos.shape;h0=self.embed(z).expand(B,-1,-1)
        h=torch.cat([h0,torch.zeros(B,N,self.irreps.dim-self.width,device=pos.device,dtype=pos.dtype)],dim=-1)
        i,j=torch.where(~torch.eye(N,dtype=torch.bool,device=pos.device))
        delta=pos[:,i]-pos[:,j];r=torch.sqrt((delta*delta).sum(-1)+1e-12)
        cutoff=.5*(torch.cos(torch.pi*r/self.cutoff)+1)*(r<self.cutoff)
        radial=torch.exp(-8*(r[...,None]-self.centers)**2)*cutoff[...,None]
        sh=o3.spherical_harmonics(self.sh,delta,normalize=True,normalization='component')
        for tp,rad in zip(self.tp,self.radial):
            weights=rad(radial)*cutoff[...,None]
            messages=tp(h[:,j],sh,weights)
            aggregate=torch.zeros_like(h).index_add_(1,i,messages)
            h=h+aggregate/max(N-1,1)
            h=torch.cat([torch.nn.functional.silu(h[...,:self.width]),h[...,self.width:]],dim=-1)
        return self.head(h[...,:self.width]).sum(dim=(1,2))


class TFNCheckpoint(Checkpoint):
    """Checkpoint compatible que conserva la procedencia de cada tramo."""
    def __init__(self,path,key,device):
        super().__init__(path,key,device);self.segments=[];self.prior_cuda_rng=None

    def save(self,model,optimizer,rng,epoch,best,best_state,best_epoch,elapsed,peak):
        self.path.parent.mkdir(parents=True,exist_ok=True)
        cuda_rng=torch.cuda.get_rng_state(self.device) if self.device.type=='cuda' else self.prior_cuda_rng
        state={'key':self.key,'epoch':epoch,'model':model.state_dict(),'optimizer':optimizer.state_dict(),
               'numpy_rng':rng.bit_generator.state,'torch_rng':torch.get_rng_state(),'cuda_rng':cuda_rng,
               'best':best,'best_state':best_state,'best_epoch':best_epoch,'elapsed':elapsed,'peak':peak,
               'segments':self.segments}
        temp=self.path.with_name(self.path.name+'.tmp');torch.save(state,temp);os.replace(temp,self.path)


def telemetry(path,device,epoch,event,error=None):
    """Muestras por época y al fallar; el uso global incluye otros procesos."""
    if not path or device.type!='cuda':return
    row={'epoch':epoch,'event':event,'unix_time':time.time()}
    if error is not None:row['error']=f'{type(error).__name__}: {error}'
    for name,fn in (('allocated_bytes',torch.cuda.memory_allocated),('reserved_bytes',torch.cuda.memory_reserved),
                    ('peak_allocated_bytes',torch.cuda.max_memory_allocated),('peak_reserved_bytes',torch.cuda.max_memory_reserved)):
        try:row[name]=fn(device)
        except Exception as exc:row[name+'_error']=str(exc)
    try:
        free,total=torch.cuda.mem_get_info(device);row['driver_free_bytes']=free;row['driver_total_bytes']=total
    except Exception as exc:row['driver_error']=str(exc)
    try:
        query=subprocess.check_output(['nvidia-smi','--query-gpu=memory.used,memory.free','--format=csv,noheader,nounits'],text=True,timeout=5)
        used,free=map(int,query.strip().splitlines()[device.index or 0].split(','))
        row['global_used_mib']=used;row['global_free_mib']=free
    except Exception as exc:row['global_error']=str(exc)
    try:
        with Path(path).open('a',encoding='utf8') as f:f.write(json.dumps(row)+'\n');f.flush()
    except OSError as exc:
        print('No se pudo escribir la telemetría:',exc,file=sys.stderr,flush=True)

def train(data,test,ntrain,lmax,epochs,batch,seed,device,checkpoint_path=None,telemetry_path=None):
    torch.manual_seed(seed);rng=np.random.default_rng(seed);perm=rng.permutation(1000);tr=perm[:ntrain];va=perm[800:]
    if ntrain>800: raise ValueError('Se reservan 200 configuraciones para validación')
    mean=float(data['energies'][tr].mean());model=SmallTensorPotential(lmax).to(device)
    optim=torch.optim.Adam(model.parameters(),lr=1e-3);best=float('inf');state=None;best_epoch=0
    gpu_start(device);start=time.perf_counter();prior_time=0.;prior_peak=0;start_epoch=0
    checkpoint=TFNCheckpoint(checkpoint_path,{'task':'so3-rmd17','lmax':lmax,'ntrain':ntrain,'epochs':epochs,'batch':batch,'seed':seed},device) if checkpoint_path else None
    saved=checkpoint.load(model,optim,rng) if checkpoint else None
    segments=[]
    if saved:
        start_epoch=saved['epoch'];best=saved['best'];state=saved['best_state'];best_epoch=saved['best_epoch'];prior_time=saved['elapsed'];prior_peak=saved['peak']
        checkpoint.prior_cuda_rng=saved.get('cuda_rng')
        segments=saved.get('segments') or [{'device':'cuda','start_epoch':0,'end_epoch':start_epoch,
                                            'seconds':prior_time,'peak_cuda_allocated_bytes':prior_peak,
                                            'source':'checkpoint anterior a registro por tramo'}]
    epoch=start_epoch
    try:
        telemetry(telemetry_path,device,epoch,'start')
        for epoch in range(start_epoch+1,epochs+1):
            model.train()
            for ids in np.array_split(rng.permutation(tr),int(np.ceil(ntrain/batch))):
                z,pos,e,f=values(data,ids,device,mean);optim.zero_grad(set_to_none=True);pe,pf=predict(model,z,pos,True)
                loss=((pe-e)**2).mean()+100*((pf-f)**2).mean();loss.backward();torch.nn.utils.clip_grad_norm_(model.parameters(),100.);optim.step()
            metrics=evaluate(model,data,va,device,mean,batch)
            if metrics['force_mae']<best:
                best=metrics['force_mae'];best_epoch=epoch;state={k:v.detach().cpu().clone() for k,v in model.state_dict().items()}
            peak=max(prior_peak,gpu_stop(device,prior_peak))
            if checkpoint:
                checkpoint.segments=segments+[{'device':device.type,'start_epoch':start_epoch,'end_epoch':epoch,
                                                'seconds':time.perf_counter()-start,
                                                'peak_cuda_allocated_bytes':gpu_stop(device) if device.type=='cuda' else None}]
                checkpoint.save(model,optim,rng,epoch,best,state,best_epoch,prior_time+time.perf_counter()-start,peak)
            telemetry(telemetry_path,device,epoch,'epoch')
            print('L',lmax,'n',ntrain,'epoch',epoch,'validation',metrics,flush=True)
        model.load_state_dict(state);metrics=evaluate(model,test,np.arange(1000),device,mean,batch);peak=max(prior_peak,gpu_stop(device,prior_peak))
        telemetry(telemetry_path,device,epoch,'test')
    except Exception as exc:
        telemetry(telemetry_path,device,epoch,'error',exc)
        raise
    return {'lmax':lmax,'n_train':ntrain,'epochs':epochs,'best_epoch':best_epoch,'val_force_mae':best,
            'test':metrics,'seconds':prior_time+time.perf_counter()-start,'peak_allocated_bytes':peak,'seed':seed,'batch_size':batch,
            'device':str(device),'device_name':torch.cuda.get_device_name(device) if device.type=='cuda' else 'CPU',
            'segments':segments+[{'device':device.type,'start_epoch':start_epoch,'end_epoch':epoch,
                                  'seconds':time.perf_counter()-start,
                                  'peak_cuda_allocated_bytes':gpu_stop(device) if device.type=='cuda' else None}],
            'parameters':sum(p.numel() for p in model.parameters()),
            'channels_per_irrep':model.width,'tensor_product_weights_per_edge':model.tp[0].weight_numel}

def checkpoint_for(output,l,n,epochs,batch,seed):
    """Preserva cada combinación; importa el formato antiguo si corresponde."""
    checkpoint=Path(f'{output}.l{l}.n{n}.checkpoint')
    legacy=Path(str(output)+'.checkpoint')
    if not checkpoint.exists() and legacy.exists():
        old=torch.load(legacy,map_location='cpu',weights_only=False)
        key=old.get('key',{})
        expected={'task':'so3-rmd17','lmax':l,'ntrain':n,'epochs':epochs,'batch':batch,'seed':seed}
        if key==expected:shutil.copy2(legacy,checkpoint)
    return checkpoint

def main():
    p=argparse.ArgumentParser();p.add_argument('--root',default='rmd17');p.add_argument('--epochs',type=int,default=100)
    p.add_argument('--sizes',type=int,nargs='+',default=[50,200,800]);p.add_argument('--lmax',type=int,nargs='+',default=[1,2,3])
    p.add_argument('--batch-size',type=int,default=8);p.add_argument('--seed',type=int,default=42);p.add_argument('--output',default='so3-results.json')
    p.add_argument('--device',choices=('cuda','cpu'),default='cuda');p.add_argument('--threads',type=int,default=4)
    p.add_argument('--telemetry',action='store_true',help='Registra memoria CUDA por época y al fallar');a=p.parse_args()
    if a.threads<1:raise ValueError('threads debe ser positivo')
    torch.set_num_threads(a.threads)
    if a.device=='cuda' and not torch.cuda.is_available(): raise RuntimeError('Se necesita CUDA')
    data,test=load_data(a.root);output=Path(a.output);results=json.loads(output.read_text(encoding='utf-8')) if output.exists() else []
    if any(r['seed']!=a.seed or r['epochs']!=a.epochs or r.get('batch_size',8)!=a.batch_size for r in results):raise ValueError('El archivo de resultados pertenece a otra semilla, lote o presupuesto')
    for l in a.lmax:
        for n in a.sizes:
            if any(r['lmax']==l and r['n_train']==n for r in results):continue
            checkpoint=checkpoint_for(output,l,n,a.epochs,a.batch_size,a.seed)
            result=train(data,test,n,l,a.epochs,a.batch_size,a.seed,torch.device(a.device),checkpoint,
                         str(checkpoint)+'.telemetry.jsonl' if a.telemetry else None)
            results.append(result);save_json(output,results);print(json.dumps(result),flush=True)

if __name__=='__main__': main()
