"""Herramientas visuomotoras para la tarea MuJoCo de p13-l01."""
import hashlib
import json
import time
from pathlib import Path
import numpy as np
import mujoco
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import resnet18, ResNet18_Weights
from p13_pusht import TareaEmpujeT, PUSHT_XML, leer_lerobot, cobertura, wilson
from p13_bc import normalizador


def softmax_espacial(features, temperature=1.0):
    if features.ndim != 4 or temperature <= 0:
        raise ValueError('Se esperan mapas B,C,H,W y temperatura positiva')
    b, c, h, w = features.shape
    p = (features.reshape(b, c, h*w) / temperature).softmax(dim=-1)
    yy, xx = torch.meshgrid(torch.linspace(-1, 1, h, device=features.device, dtype=features.dtype),
                            torch.linspace(-1, 1, w, device=features.device, dtype=features.dtype), indexing='ij')
    return torch.stack(((p*xx.flatten()).sum(-1), (p*yy.flatten()).sum(-1)), dim=-1)


def cambiar_bn_a_gn(module):
    """Transfiere gamma/beta, pero no confunde estadísticas de BN con GN."""
    for name, child in module.named_children():
        if isinstance(child, nn.BatchNorm2d):
            new = nn.GroupNorm(32, child.num_features, eps=child.eps)
            with torch.no_grad():
                new.weight.copy_(child.weight)
                new.bias.copy_(child.bias)
            setattr(module, name, new)
        else:
            cambiar_bn_a_gn(child)
    return module


class Visuomotora(nn.Module):
    def __init__(self, pretrained=True, cameras=2):
        super().__init__()
        weights = ResNet18_Weights.IMAGENET1K_V1 if pretrained else None
        model = cambiar_bn_a_gn(resnet18(weights=weights))
        self.encoder = nn.Sequential(model.conv1, model.bn1, model.relu, model.maxpool,
                                     model.layer1, model.layer2, model.layer3, model.layer4)
        self.head = nn.Sequential(nn.Linear(cameras*1024+2, 256), nn.ReLU(), nn.Linear(256, 2))
        self.cameras = cameras
        self.register_buffer('mean', torch.tensor([0.485, 0.456, 0.406])[None, :, None, None])
        self.register_buffer('std', torch.tensor([0.229, 0.224, 0.225])[None, :, None, None])

    def forward(self, images, proprio):
        b, n, c, h, w = images.shape
        if n != self.cameras or c != 3:
            raise ValueError('Número de cámaras o canales incompatible')
        x = images.reshape(b*n, c, h, w).float() / 255.
        x = (x - self.mean) / self.std
        features = self.encoder(x)
        points = softmax_espacial(features).reshape(b, n*1024)
        return self.head(torch.cat([points, proprio], dim=1))


def recorte_compartido(images, padding=4):
    """Mismo desplazamiento por ejemplo en todas sus cámaras, conservando tamaño."""
    b, n, c, h, w = images.shape
    x = images.reshape(b, n*c, h, w).float()
    offsets = torch.randint(-padding, padding+1, (b, 2), device=images.device).float()
    theta = torch.zeros(b, 2, 3, device=images.device)
    theta[:, 0, 0], theta[:, 1, 1] = 1, 1
    theta[:, 0, 2], theta[:, 1, 2] = 2*offsets[:, 0]/w, 2*offsets[:, 1]/h
    grid = F.affine_grid(theta, x.shape, align_corners=False)
    x = F.grid_sample(x, grid, padding_mode='border', align_corners=False)
    brightness = torch.empty(b, 1, 1, 1, device=images.device).uniform_(0.9, 1.1)
    return (x * brightness).clamp(0, 255).reshape(b, n, c, h, w)


def tarea_con_dos_camaras():
    xml = PUSHT_XML.replace('</worldbody>',
        '<camera name="inclinada" pos="0.256 -0.30 0.60" xyaxes="1 0 0 0 0.73 0.68" fovy="45"/></worldbody>')
    task = TareaEmpujeT()
    task.env.model = mujoco.MjModel.from_xml_string(xml)
    task.env.data = mujoco.MjData(task.env.model)
    task.env.renderer = None
    return task


def imagenes(task):
    env = task.env
    if env.renderer is None:
        env.renderer = mujoco.Renderer(env.model, 96, 96)
    out = []
    for camera in ('arriba', 'inclinada'):
        env.renderer.update_scene(env.data, camera=camera)
        out.append(np.flipud(env.renderer.render()).copy())
    return np.stack(out)


def huella_camaras(root):
    """Invalida la caché si cambian los datos, MuJoCo o el contrato de cámara."""
    root = Path(root)
    digest = hashlib.sha256()
    digest.update(('p13-vision-v2:' + mujoco.__version__ + ':' + PUSHT_XML + ':' +
                   'inclinada:0.256,-0.30,0.60:xyaxes=1,0,0,0,0.73,0.68:fovy=45:' +
                   '96x96:arriba,inclinada:flipud:uint8').encode('utf-8'))
    for path in sorted(p for p in root.rglob('*') if p.is_file()):
        digest.update(path.relative_to(root).as_posix().encode('utf-8'))
        with path.open('rb') as source:
            for block in iter(lambda: source.read(1024*1024), b''):
                digest.update(block)
    return digest.hexdigest()


def preparar_imagenes(root, cache):
    """Reproduce cada episodio y conserva imágenes de ambas cámaras antes de actuar."""
    info, _, episodes, provenance = leer_lerobot(root)
    cache = Path(cache)
    cache.mkdir(parents=True, exist_ok=True)
    fingerprint = huella_camaras(root)
    manifest = cache / 'manifest.json'
    if manifest.exists():
        metadata = json.loads(manifest.read_text(encoding='utf-8'))
        if metadata['sha256'] != fingerprint or 'files' not in metadata:
            raise ValueError('La caché pertenece a otro conjunto o versión: elige otra carpeta')
    elif any(cache.glob('episode-*.npy')):
        raise ValueError('Caché existente sin manifiesto verificable: elige otra carpeta')
    else:
        metadata = {'sha256': fingerprint, 'files': {}}
        manifest.write_text(json.dumps(metadata), encoding='utf-8')
    task = tarea_con_dos_camaras()
    for idx, (episode, meta) in enumerate(zip(episodes, provenance)):
        target = cache / f'episode-{idx:03d}.npy'
        if target.exists():
            cached = np.load(target, mmap_mode='r')
            if cached.shape != (len(episode['action']), 2, 96, 96, 3) or cached.dtype != np.uint8:
                raise ValueError(f'Caché incompleta en {target}')
            with target.open('rb') as source:
                file_hash = hashlib.file_digest(source, 'sha256').hexdigest()
            if metadata['files'].get(target.name) != file_hash:
                raise ValueError(f'Hash de caché incompatible en {target}')
            continue
        task.reiniciar(meta['semilla'])
        task.fijar_estado(np.asarray(meta['estado_inicial']))
        frames = []
        for t, action in enumerate(episode['action']):
            obs = task.observar(False)
            if not np.array_equal(obs['observation.environment_state'].astype('float32'), episode['observation.environment_state'][t]):
                raise RuntimeError(f'No se reprodujo el estado del episodio {idx}, paso {t}')
            frames.append(imagenes(task))
            task.actuar(action)
        temporary = cache / f'episode-{idx:03d}.part.npy'
        np.save(temporary, np.stack(frames), allow_pickle=False)
        temporary.replace(target)
        with target.open('rb') as source:
            metadata['files'][target.name] = hashlib.file_digest(source, 'sha256').hexdigest()
        temporary_manifest = manifest.with_suffix('.json.tmp')
        temporary_manifest.write_text(json.dumps(metadata), encoding='utf-8')
        temporary_manifest.replace(manifest)
        print('imágenes episodio', idx, len(frames), flush=True)
    if task.env.renderer is not None:
        task.env.renderer.close()
    return info


def medir_latencia(net, device, repeats=100):
    net.eval()
    images = torch.zeros((1, 2, 3, 96, 96), device=device, dtype=torch.uint8)
    proprio = torch.zeros((1, 2), device=device)
    timings = []
    if device.type == 'cuda':
        torch.cuda.reset_peak_memory_stats()
    with torch.no_grad():
        for i in range(repeats+20):
            if device.type == 'cuda':
                torch.cuda.synchronize()
            start = time.perf_counter()
            net(images, proprio)
            if device.type == 'cuda':
                torch.cuda.synchronize()
            if i >= 20:
                timings.append((time.perf_counter()-start)*1000)
    return {'median_ms': float(np.median(timings)), 'p95_ms': float(np.quantile(timings, 0.95)),
            'peak_allocated_bytes': int(torch.cuda.max_memory_allocated()) if device.type == 'cuda' else None}


def desplegar(net, stats, seeds, device, progress=None, contract=None):
    """Mismas semillas de control que BC; el render se realiza antes de cada acción."""
    pm, ps, am, ast = stats
    net.eval()
    results = []
    progress = Path(progress) if progress is not None else None
    if progress is not None and progress.exists():
        saved = json.loads(progress.read_text(encoding='utf-8'))
        if saved['contract'] != contract or [r['seed'] for r in saved['episodes']] != list(seeds)[:len(saved['episodes'])]:
            raise ValueError('La evaluación guardada no coincide con el contrato')
        results = saved['episodes']
    with torch.no_grad():
        for seed in list(seeds)[len(results):]:
            task = tarea_con_dos_camaras()
            task.reiniciar(int(seed))
            success, path, coverage = False, [], []
            for t in range(300):
                o = task.observar(False)
                x = torch.as_tensor(((o['observation.state']-pm)/ps)[None], dtype=torch.float32, device=device)
                image = np.transpose(imagenes(task), (0, 3, 1, 2)).copy()
                pixels = torch.as_tensor(image[None], dtype=torch.uint8, device=device)
                pred = net(pixels, x).cpu().numpy()[0] * ast + am
                _, _, ok, done = task.actuar(pred)
                pose = task.env.pose()
                path.append(pose.tolist())
                coverage.append(cobertura(pose))
                success |= bool(ok)
                if done:
                    break
            if task.env.renderer is not None:
                task.env.renderer.close()
            results.append({'seed': int(seed), 'success': success, 'steps': t+1,
                            'coverage': coverage, 'object_path': path})
            if progress is not None:
                tmp = progress.with_suffix(progress.suffix + '.tmp')
                tmp.write_text(json.dumps({'contract': contract, 'episodes': results}), encoding='utf-8')
                tmp.replace(progress)
    k = sum(r['success'] for r in results)
    return {'n': len(results), 'successes': k, 'wilson': list(map(float, wilson(k, len(results)))), 'episodes': results}


def experimento(root, cache, output, seeds=(0, 1, 2), epochs=20, eval_seeds=None, n_train=None):
    info = preparar_imagenes(root, cache)
    _, _, episodes, _ = leer_lerobot(root)
    train_end = int(info['splits']['train'].split(':')[1])
    samples = [np.load(Path(cache) / f'episode-{i:03d}.npy', mmap_mode='r') for i in range(len(episodes))]
    p = np.concatenate([e['observation.state'] for e in episodes]).astype('float32')
    a = np.concatenate([e['action'] for e in episodes]).astype('float32')
    n_train = train_end if n_train is None else n_train
    if not 1 <= n_train <= train_end:
        raise ValueError('n_train fuera de la partición de entrenamiento')
    train_count = sum(len(e['action']) for e in episodes[:n_train])
    valid_start = sum(len(e['action']) for e in episodes[:train_end])
    pm, ps = normalizador(p[:train_count])
    am, ast = normalizador(a[:train_count])
    stats = tuple(np.asarray(x, dtype='float32') for x in (pm, ps, am, ast))
    data = np.concatenate(samples, axis=0).transpose(0, 1, 4, 2, 3)
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print('dispositivo', device, 'entrenamiento', train_count, 'validación', len(a)-valid_start, flush=True)
    test_seeds = list(range(20000, 20100)) if eval_seeds is None else list(eval_seeds)
    output = Path(output)
    output.mkdir(parents=True, exist_ok=True)
    results_file = output / 'results.json'
    results = json.loads(results_file.read_text(encoding='utf-8')) if results_file.exists() else []
    source_hash = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
    dataset_hash = huella_camaras(root)
    for seed in seeds:
        for augment in (False, True):
            name = f'vision-{seed}-{int(augment)}'
            checkpoint = output / (name+'.pt')
            resume = output / (name+'.resume.pt')
            progress = output / (name+'.eval.json')
            contract = {'dataset': dataset_hash, 'code': source_hash, 'torch': torch.__version__,
                        'seed': int(seed), 'augment': augment, 'epochs': epochs, 'n_train': n_train,
                        'test_seeds': test_seeds, 'device': device.type, 'batch': 64, 'microbatch': 16}
            found = [r for r in results if r['seed'] == seed and r['augment'] == augment]
            if found:
                if len(found) != 1 or found[0].get('contract') != contract or not checkpoint.exists():
                    raise ValueError('Resultado previo incompatible o sin checkpoint')
                continue
            torch.manual_seed(int(seed))
            gen = torch.Generator(device='cpu').manual_seed(int(seed))
            model = Visuomotora(pretrained=True).to(device)
            optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)
            scaler = torch.amp.GradScaler('cuda', enabled=device.type == 'cuda')
            best, best_state, completed = float('inf'), None, 0
            if checkpoint.exists():
                saved = torch.load(checkpoint, map_location='cpu', weights_only=False)
                if saved.get('contract') != contract:
                    raise ValueError('Checkpoint previo incompatible')
                best_state, best, completed = saved['state_dict'], saved['validation_mse'], epochs
            elif resume.exists():
                saved = torch.load(resume, map_location=device, weights_only=False)
                if saved['contract'] != contract:
                    raise ValueError('Entrenamiento reanudable incompatible')
                model.load_state_dict(saved['state_dict'])
                optimizer.load_state_dict(saved['optimizer'])
                scaler.load_state_dict(saved['scaler'])
                best_state, best, completed = saved['best_state'], saved['best'], saved['epoch']
                gen.set_state(saved['generator'].cpu())
                torch.set_rng_state(saved['torch_rng'].cpu())
                if device.type == 'cuda':
                    torch.cuda.set_rng_state(saved['cuda_rng'].cpu(), device)
            for epoch in range(completed+1, epochs+1):
                model.train()
                for indices in torch.randperm(train_count, generator=gen).split(64):
                    optimizer.zero_grad(set_to_none=True)
                    # Una actualización por lote efectivo; el último microbatch puede ser menor.
                    for micro in indices.split(16):
                        idx = micro.numpy()
                        images = torch.as_tensor(data[idx].copy(), device=device)
                        images = recorte_compartido(images, padding=4 if augment else 0)
                        proprio = torch.as_tensor((p[idx]-pm)/ps, device=device)
                        target = torch.as_tensor((a[idx]-am)/ast, device=device)
                        with torch.amp.autocast(device_type=device.type, enabled=device.type == 'cuda'):
                            loss = (model(images, proprio)-target).square().mean()
                        scaler.scale(loss * (len(micro) / len(indices))).backward()
                    scaler.step(optimizer)
                    scaler.update()
                model.eval()
                val_sum, val_count = 0., 0
                with torch.no_grad():
                    for start in range(valid_start, len(a), 16):
                        idx = np.arange(start, min(start+16, len(a)))
                        images = torch.as_tensor(data[idx].copy(), device=device)
                        pred = model(images, torch.as_tensor((p[idx]-pm)/ps, device=device))
                        target = torch.as_tensor((a[idx]-am)/ast, device=device)
                        val_sum += float((pred-target).square().sum().cpu())
                        val_count += target.numel()
                val = val_sum/val_count
                if val < best:
                    best = val
                    best_state = {k: v.detach().cpu().clone() for k, v in model.state_dict().items()}
                state = {'contract': contract, 'epoch': epoch, 'state_dict': model.state_dict(),
                         'optimizer': optimizer.state_dict(), 'scaler': scaler.state_dict(), 'best': best,
                         'best_state': best_state, 'generator': gen.get_state(), 'torch_rng': torch.get_rng_state(),
                         'cuda_rng': torch.cuda.get_rng_state(device) if device.type == 'cuda' else None}
                tmp = resume.with_suffix(resume.suffix + '.tmp')
                torch.save(state, tmp)
                tmp.replace(resume)
                print('seed', seed, 'augment', augment, 'epoch', epoch, 'validation', val, flush=True)
            model.load_state_dict(best_state)
            if not checkpoint.exists():
                tmp = checkpoint.with_suffix(checkpoint.suffix + '.tmp')
                torch.save({'state_dict': best_state, 'stats': stats, 'augment': augment, 'seed': seed,
                            'validation_mse': best, 'contract': contract}, tmp)
                tmp.replace(checkpoint)
            if resume.exists():
                resume.unlink()
            timing = medir_latencia(model, device)
            with checkpoint.open('rb') as f:
                checkpoint_sha = hashlib.file_digest(f, 'sha256').hexdigest()
            rollout_contract = {'checkpoint': checkpoint_sha, 'test_seeds': test_seeds, 'device': device.type, 'batch': 64, 'microbatch': 16}
            rollouts = desplegar(model, stats, test_seeds, device, progress=progress, contract=rollout_contract)
            record = {'seed': seed, 'augment': augment, 'validation_mse': best, 'latency': timing,
                      'rollouts': rollouts, 'contract': contract}
            results.append(record)
            tmp = results_file.with_suffix(results_file.suffix + '.tmp')
            tmp.write_text(json.dumps(results, ensure_ascii=False), encoding='utf-8')
            tmp.replace(results_file)
            if progress.exists():
                progress.unlink()
            print(name, 'success', rollouts['successes'], '/', rollouts['n'], timing, flush=True)
    return results
