"""Experimento reproducible de ogbn-arxiv. Ejecuta --help para opciones y presupuesto."""
import argparse
import copy
import json
import hashlib
import time
import platform
from pathlib import Path
import numpy as np
import torch
import torch_geometric
import ogb
from torch import nn
from torch.nn import functional as F
from torch_geometric.data import Data
from torch_geometric.data.data import DataEdgeAttr, DataTensorAttr
from torch_geometric.data.storage import GlobalStorage
from torch_geometric.loader import NeighborLoader, ClusterData, ClusterLoader
from torch_geometric.nn import SAGEConv, GCNConv, GATConv
from torch_geometric.utils import to_undirected
from ogb.nodeproppred import PygNodePropPredDataset, Evaluator

parser=argparse.ArgumentParser()
parser.add_argument('--root',default=str(Path.home()/'.cache'/'oryon'/'datasets'/'OGB'))
parser.add_argument('--strategy',choices=['full','neighbors','clusters'],default='full')
parser.add_argument('--model',choices=['sage','gcn','gat'],default='sage')
parser.add_argument('--epochs',type=int,default=100)
parser.add_argument('--patience',type=int,default=15)
parser.add_argument('--seeds',type=int,default=5)
parser.add_argument('--output',default='ogbn-arxiv-results.json')
parser.add_argument('--checkpoint',default='ogbn-arxiv-checkpoint.pt')
parser.add_argument('--resume',action='store_true')
parser.add_argument('--assignment',default=None,help='JSON de partición METIS externa opcional')
parser.add_argument('--device',choices=['auto','cpu','cuda'],default='auto',help='Dispositivo explícito para reproducir o diagnosticar')
args=parser.parse_args()
if args.model!='sage' and args.strategy!='full':
    parser.error('La inferencia por capas de este script está implementada para SAGE en minibatches')
if args.epochs<1 or args.seeds<1 or args.patience<1: parser.error('Presupuestos deben ser positivos')
torch.set_num_threads(4)
device=torch.device(('cuda' if torch.cuda.is_available() else 'cpu') if args.device=='auto' else args.device)
if device.type=='cuda' and not torch.cuda.is_available(): parser.error('CUDA no está disponible')
with torch.serialization.safe_globals([Data,DataEdgeAttr,DataTensorAttr,GlobalStorage]):
    dataset=PygNodePropPredDataset(name='ogbn-arxiv',root=args.root)
    graph=dataset[0]; split=dataset.get_idx_split()
graph.y=graph.y.view(-1)
original_edges=graph.num_edges
graph.edge_index=to_undirected(graph.edge_index,num_nodes=graph.num_nodes)
graph.train_mask=torch.zeros(graph.num_nodes,dtype=torch.bool); graph.train_mask[split['train']]=True
evaluator=Evaluator(name='ogbn-arxiv')
classes=dataset.num_classes

class Net(nn.Module):
    def __init__(self,kind):
        super().__init__(); self.kind=kind
        if kind=='sage': self.layers=nn.ModuleList([SAGEConv(graph.num_features,128),SAGEConv(128,classes)])
        elif kind=='gcn': self.layers=nn.ModuleList([GCNConv(graph.num_features,128),GCNConv(128,classes)])
        else: self.layers=nn.ModuleList([GATConv(graph.num_features,32,heads=4),GATConv(128,classes,heads=1,concat=False)])
    def forward(self,x,edge):
        x=F.dropout(x,p=.5,training=self.training)
        x=F.relu(self.layers[0](x,edge))
        x=F.dropout(x,p=.5,training=self.training)
        return self.layers[1](x,edge)

def eval_full(model,data):
    model.eval()
    with torch.no_grad(): return model(data.x,data.edge_index).argmax(-1).cpu().view(-1,1)

def eval_layerwise(model,data,loader=None):
    model.eval(); x=data.x
    if loader is None:
        loader=NeighborLoader(data,num_neighbors=[-1],batch_size=2048,shuffle=False,num_workers=0)
    with torch.no_grad():
        for i,layer in enumerate(model.layers):
            out=torch.empty((data.num_nodes,layer.out_channels))
            for batch in loader:
                n_id=batch.n_id; count=batch.batch_size
                h=layer(x[n_id].to(device),batch.edge_index.to(device))[:count]
                if i==0: h=F.relu(h)
                out[n_id[:count]]=h.cpu()
            x=out
    return x.argmax(-1).view(-1,1)

def score(pred,key):
    idx=split[key]
    return evaluator.eval({'y_true':graph.y[idx].view(-1,1),'y_pred':pred[idx]})['acc']

partition=None; partition_generation_seconds=0.
if args.strategy=='clusters':
    t0=time.perf_counter()
    if args.assignment:
        assignment=json.loads(Path(args.assignment).read_text(encoding='utf-8'))
        partition_generation_seconds=float(assignment['elapsed_seconds'])
        source=Path(args.root)/'ogbn_arxiv'/'raw'/'edge.csv.gz'
        digest=hashlib.sha256(source.read_bytes()).hexdigest()
        if assignment['source_sha256']!=digest or assignment['nodes']!=graph.num_nodes or assignment['parts']!=128:
            raise ValueError('La partición no corresponde al grafo o al número de partes')
        membership=torch.tensor(assignment['members'],dtype=torch.long)
        if membership.numel()!=graph.num_nodes or int(membership.min())<0 or int(membership.max())>=128:
            raise ValueError('Asignación de nodos inválida')
        class AssignedClusterData(ClusterData):
            def _metis(self,edge_index,num_nodes): return membership
        partition=AssignedClusterData(graph,num_parts=128)
    else:
        partition=ClusterData(graph,num_parts=128,save_dir=str(Path(args.root)/'cluster-arxiv-128'))
    partition_seconds=time.perf_counter()-t0
else: partition_seconds=0.
full_graph=copy.copy(graph).to(device) if args.strategy=='full' else None
# La topología no cambia: reutiliza el sampler sin copiar los atributos originales en cada lote.
inference_loader=(NeighborLoader(Data(edge_index=graph.edge_index,num_nodes=graph.num_nodes),
                  num_neighbors=[-1],batch_size=2048,shuffle=False,num_workers=0)
                  if args.strategy!='full' else None)
identity=hashlib.sha256()
for file in sorted((Path(args.root)/'ogbn_arxiv'/'raw').glob('*.csv.gz')):
    identity.update(file.name.encode())
    with file.open('rb') as stream: identity.update(hashlib.file_digest(stream,'sha256').digest())
for key in ('train','valid','test'):
    identity.update(key.encode()); identity.update(split[key].numpy().tobytes())
if args.assignment:
    with Path(args.assignment).open('rb') as stream: identity.update(hashlib.file_digest(stream,'sha256').digest())
if partition is not None:
    identity.update(partition.partition.node_perm.cpu().numpy().tobytes())
    identity.update(partition.partition.partptr.cpu().numpy().tobytes())
identity=identity.hexdigest()
config={k:getattr(args,k) for k in ('strategy','model','epochs','patience','seeds')}
source_hash=hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
checkpoint=Path(args.checkpoint)
def save(state,path=checkpoint):
    path.parent.mkdir(parents=True,exist_ok=True)
    temp=path.with_name(path.name+'.tmp'); torch.save(state,temp); temp.replace(path)
def save_json(path,value):
    path=Path(path);path.parent.mkdir(parents=True,exist_ok=True)
    temp=path.with_name(path.name+'.tmp');temp.write_text(json.dumps(value,indent=2),encoding='utf-8');temp.replace(path)
results=[]; resume_state=None; first_seed=0
if args.resume:
    resume_state=torch.load(checkpoint,map_location=device,weights_only=True)
    if resume_state['identity']!=identity or resume_state['config']!=config or resume_state['torch']!=str(torch.__version__) or resume_state['device']!=str(device) or resume_state.get('source_hash')!=source_hash:
        raise ValueError('El checkpoint no coincide con datos, configuración, dispositivo o versión')
    results=resume_state['results']; first_seed=resume_state['seed']
for seed in range(first_seed,args.seeds):
    torch.manual_seed(seed); torch.cuda.manual_seed_all(seed)
    model=Net(args.model).to(device); opt=torch.optim.Adam(model.parameters(),lr=.01,weight_decay=5e-4)
    best=-1.; best_epoch=0; state=None; stale=0; times=[]; peaks=[]; val_times=[]; val_peaks=[]; first_epoch=1
    if args.strategy=='neighbors':
        loader=NeighborLoader(graph,input_nodes=split['train'],num_neighbors=[15,10],batch_size=1024,shuffle=True,num_workers=0)
    elif args.strategy=='clusters': loader=ClusterLoader(partition,batch_size=8,shuffle=True,num_workers=0)
    if resume_state is not None and resume_state['seed']==seed and resume_state['model'] is not None:
        model.load_state_dict(resume_state['model']); opt.load_state_dict(resume_state['optimizer'])
        best=resume_state['best']; best_epoch=resume_state['best_epoch']; state=resume_state['best_model']; stale=resume_state['stale']
        times=resume_state['times']; peaks=resume_state['peaks']; val_times=resume_state['val_times']; val_peaks=resume_state['val_peaks']; first_epoch=resume_state['epoch']+1
        torch.set_rng_state(resume_state['rng_cpu'].cpu())
        if device.type=='cuda':
            if resume_state['rng_cuda'] is None: raise ValueError('El checkpoint no tiene RNG CUDA')
            torch.cuda.set_rng_state_all([v.cpu() for v in resume_state['rng_cuda']])
    for epoch in range(first_epoch,args.epochs+1):
        if stale>=args.patience: break
        model.train()
        if device.type=='cuda': torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats()
        t0=time.perf_counter()
        if args.strategy=='full':
            opt.zero_grad(); logits=model(full_graph.x,full_graph.edge_index)
            loss=F.cross_entropy(logits[full_graph.train_mask],full_graph.y[full_graph.train_mask]); loss.backward(); opt.step()
        else:
            for batch in loader:
                batch=batch.to(device); opt.zero_grad(); logits=model(batch.x,batch.edge_index)
                if args.strategy=='neighbors': mask=slice(0,batch.batch_size)
                else: mask=batch.train_mask
                if args.strategy=='clusters' and not bool(mask.any()): continue
                loss=F.cross_entropy(logits[mask],batch.y[mask]); loss.backward(); opt.step()
        if device.type=='cuda': torch.cuda.synchronize()
        times.append(time.perf_counter()-t0)
        peaks.append(torch.cuda.max_memory_allocated() if device.type=='cuda' else None)
        if device.type=='cuda': torch.cuda.reset_peak_memory_stats()
        t0=time.perf_counter()
        pred=eval_full(model,full_graph) if args.strategy=='full' else eval_layerwise(model,graph,inference_loader)
        if device.type=='cuda': torch.cuda.synchronize()
        val_times.append(time.perf_counter()-t0)
        val_peaks.append(torch.cuda.max_memory_allocated() if device.type=='cuda' else None)
        val=score(pred,'valid')
        if val>best:
            best=val; best_epoch=epoch; state=copy.deepcopy(model.state_dict()); stale=0
        else: stale+=1
        print('seed',seed,'epoch',epoch,'valid',round(val,6),flush=True)
        save({'identity':identity,'config':config,'torch':str(torch.__version__),'device':str(device),'source_hash':source_hash,'seed':seed,'epoch':epoch,
              'model':model.state_dict(),'optimizer':opt.state_dict(),'best':best,'best_epoch':best_epoch,'best_model':state,
              'stale':stale,'times':times,'peaks':peaks,'val_times':val_times,'val_peaks':val_peaks,'results':results,'rng_cpu':torch.get_rng_state(),
              'rng_cuda':torch.cuda.get_rng_state_all() if device.type=='cuda' else None})
        if stale>=args.patience: break
    model.load_state_dict(state)
    if device.type=='cuda': torch.cuda.synchronize(); torch.cuda.reset_peak_memory_stats()
    t0=time.perf_counter()
    pred=eval_full(model,full_graph) if args.strategy=='full' else eval_layerwise(model,graph,inference_loader)
    if device.type=='cuda': torch.cuda.synchronize()
    test_seconds=time.perf_counter()-t0
    test_peak=torch.cuda.max_memory_allocated() if device.type=='cuda' else None
    result={'seed':seed,'best_epoch':best_epoch,'valid':best,'test':score(pred,'test'),
            'mean_train_seconds_per_epoch':float(np.mean(times)),
            'peak_allocated_bytes':max(peaks) if device.type=='cuda' else None,
            'mean_validation_seconds_per_epoch':float(np.mean(val_times)),
            'peak_validation_allocated_bytes':max(val_peaks) if device.type=='cuda' else None,
            'test_evaluation_seconds':test_seconds,'test_peak_allocated_bytes':test_peak}
    save({'identity':identity,'config':config,'torch':str(torch.__version__),'device':str(device),'source_hash':source_hash,
          'seed':seed,'best_epoch':best_epoch,'best_model':state,'result':result},
         checkpoint.with_name(checkpoint.name+f'.seed-{seed}.best'))
    results.append(result); print(json.dumps(result),flush=True)
    save_json(args.output,{'status':'in_progress','results':results})
    save({'identity':identity,'config':config,'torch':str(torch.__version__),'device':str(device),'source_hash':source_hash,'seed':seed+1,'epoch':0,
          'model':None,'optimizer':None,'best':None,'best_epoch':0,'best_model':None,'stale':0,'times':[],'peaks':[],'val_times':[],'val_peaks':[],
          'results':results,'rng_cpu':torch.get_rng_state(),'rng_cuda':torch.cuda.get_rng_state_all() if device.type=='cuda' else None})
    resume_state=None
summary={'model':args.model,'strategy':args.strategy,'epochs_max':args.epochs,'patience':args.patience,
         'device':str(device),'torch':torch.__version__,'nodes':graph.num_nodes,'original_directed_edges':original_edges,
         'gpu':torch.cuda.get_device_name(device) if device.type=='cuda' else None,
         'python':platform.python_version(),'pyg':torch_geometric.__version__,'ogb':ogb.__version__,
         'source_sha256':source_hash,'data_identity_sha256':identity,
         'symmetrized_edges':graph.num_edges,'partition_seconds':partition_seconds,'partition_generation_seconds':partition_generation_seconds,'results':results,
         'mean_test':float(np.mean([r['test'] for r in results])),
         'sd_test':float(np.std([r['test'] for r in results],ddof=1)) if len(results)>1 else None}
save_json(args.output,summary)
print(json.dumps(summary,indent=2),flush=True)
