"""Migra una copia QM9 naive_aug a la variante CUDA con rotaciones generadas en CPU.

Requiere la evidencia del contraste y ambos programas exactos. No modifica el
checkpoint de origen y no promete identidad numérica entre CPU y CUDA.
"""
import argparse
import copy
import hashlib
import io
import json
import os
from pathlib import Path
import torch

p=argparse.ArgumentParser()
for flag in ('source','destination','original-script','candidate-script','proof'):
    p.add_argument('--'+flag,type=Path,required=True)
p.add_argument('--expected-epoch',type=int,required=True)
p.add_argument('--cuda-rng-seed',type=int,default=0)
a=p.parse_args()
sha=lambda path:hashlib.sha256(path.read_bytes()).hexdigest()
old_sha=sha(a.original_script);new_sha=sha(a.candidate_script);proof=json.loads(a.proof.read_text(encoding='utf8'))
if not (proof.get('passed') and proof.get('cpu_original_candidate_bitwise') and proof.get('batch_indices_rotations_cpu_rng_sampler_identical')
        and proof.get('outputs_and_validation_close') and proof.get('losses_close')
        and proof.get('tolerances_predeclared')=={'output_atol':2e-5,'output_rtol':2e-4,'loss_atol':1e-5,'loss_rtol':1e-4,
                                                  'max_gradient_abs':2e-4,'max_weight_abs_after_eight':1e-3,'max_adam_abs_after_eight':1e-3}
        and proof.get('max_gradient_abs',float('inf'))<=2e-4 and proof.get('max_final_weight_abs',float('inf'))<=1e-3
        and proof.get('max_final_adam_abs',float('inf'))<=1e-3
        and proof.get('original_sha256')==old_sha and proof.get('candidate_sha256')==new_sha):
    raise ValueError('Falta evidencia compatible de rotaciones, RNG y códigos')
if a.source.resolve()==a.destination.resolve() or a.destination.exists():raise ValueError('El destino debe ser una ruta nueva')
if not torch.cuda.is_available() or torch.cuda.device_count()!=1:raise RuntimeError('Se requiere exactamente una CUDA visible')
raw=a.source.read_bytes();saved=torch.load(io.BytesIO(raw),map_location='cpu',weights_only=True)
if (saved['device']!='cpu' or saved['rng_cuda'] is not None or saved['epoch']!=a.expected_epoch
        or saved['config']['model']!='naive_aug' or saved['script_sha256']!=old_sha or saved['torch']!=str(torch.__version__)):
    raise ValueError('Checkpoint de otra época, variante, código o versión')
converted=copy.deepcopy(saved);torch.cuda.manual_seed_all(a.cuda_rng_seed)
converted.update(device='cuda',script_sha256=new_sha,rng_cuda=[x.cpu() for x in torch.cuda.get_rng_state_all()])
def equal(x,y):
    if torch.is_tensor(x):return torch.is_tensor(y) and torch.equal(x,y)
    if isinstance(x,dict):return isinstance(y,dict) and x.keys()==y.keys() and all(equal(x[k],y[k]) for k in x)
    if isinstance(x,(list,tuple)):return type(x)==type(y) and len(x)==len(y) and all(equal(a,b) for a,b in zip(x,y))
    return x==y
a.destination.parent.mkdir(parents=True,exist_ok=True);tmp=a.destination.with_name(a.destination.name+'.tmp')
torch.save(converted,tmp);os.replace(tmp,a.destination);check=torch.load(a.destination,map_location='cpu',weights_only=True)
if not (all(equal(saved[k],check[k]) for k in saved if k not in ('device','script_sha256','rng_cuda'))
        and check['device']=='cuda' and check['script_sha256']==new_sha and equal(check['rng_cuda'],converted['rng_cuda'])):
    raise RuntimeError('La copia migrada no conserva el estado esperado')
record={'source_sha256':hashlib.sha256(raw).hexdigest(),'destination_sha256':sha(a.destination),'epoch':saved['epoch'],
        'original_script_sha256':old_sha,'candidate_script_sha256':new_sha,'proof_sha256':sha(a.proof),
        'cuda_rng_seed':a.cuda_rng_seed,'data_and_split_identity':saved['identity'],'config':saved['config'],
        'unchanged':['model','optimizer','best_model','best','best_epoch','stale','rng_cpu','loader_rng'],
        'note':'Rotaciones calculadas en CPU; código y backend cambiaron. No se promete trayectoria idéntica.'}
sidecar=a.destination.with_name(a.destination.name+'.migration.json')
sidecar.write_text(json.dumps(record,indent=2,ensure_ascii=False),encoding='utf8');print(json.dumps(record,ensure_ascii=False))
