"""Batería prospectiva base/LoRA con una sola carga y grupos reanudables.

El manifiesto fija todas las condiciones antes de evaluar. Cada resultado
conserva el contrato que consume export_language_rollouts.py.
"""
import argparse
import hashlib
from importlib.metadata import version
import json
import math
import os
import time
from pathlib import Path

import numpy as np
import psutil
import torch

from language_tasks import LanguageTask
from lora_utils import matching_fingerprints
from p13_pusht import wilson
from portable_checkpoint import load_trained_checkpoint
from smolvla_adapter import training_stats
from smolvla_batched_eval import run_group
from train_smolvla_lora import config_fingerprints, construct
from training_resume import dataset_fingerprints
from window_data import load_episodes

CASES = [
    {'name': 'literal-azul', 'goal': 'azul', 'second_goal': None, 'instruction': 'Empuja la T hasta la meta azul'},
    {'name': 'literal-naranja', 'goal': 'naranja', 'second_goal': None, 'instruction': 'Empuja la T hasta la meta naranja'},
    {'name': 'parafrasis-azul', 'goal': 'azul', 'second_goal': None, 'instruction': 'Lleva la T al objetivo azul'},
    {'name': 'parafrasis-naranja', 'goal': 'naranja', 'second_goal': None, 'instruction': 'Lleva la T al objetivo naranja'},
    {'name': 'secuencia-azul-naranja', 'goal': 'azul', 'second_goal': 'naranja',
     'instruction': 'Primero empuja la T a la meta azul y después a la naranja'},
    {'name': 'secuencia-naranja-azul', 'goal': 'naranja', 'second_goal': 'azul',
     'instruction': 'Primero empuja la T a la meta naranja y después a la azul'},
]


def sha(path):
    with Path(path).open('rb') as stream:
        return hashlib.file_digest(stream, 'sha256').hexdigest()


def atomic_json(path, payload):
    path = Path(path)
    tmp = Path(str(path) + '.tmp')
    tmp.write_text(json.dumps(payload, ensure_ascii=False, allow_nan=False), encoding='utf-8')
    os.replace(tmp, path)


def check_records(records, contract):
    if [r['seed'] for r in records] != list(range(contract['eval_seed'], contract['eval_seed'] + len(records))):
        raise ValueError('Semillas parciales incompatibles')
    if len(records) > contract['episodes']:
        raise ValueError('Demasiadas escenas')
    for record in records:
        trace = record['trace']
        if type(record['success']) is not bool or record['steps'] != len(trace) or not 1 <= len(trace) <= 300:
            raise ValueError('Episodio incompatible')
        for frame in trace:
            if (len(frame['action']) != 2 or len(frame['raw_action']) != 2 or len(frame['agent']) != 2 or
                len(frame['object']) != 2 or frame['phase'] not in (0, 1) or
                not all(math.isfinite(v) for v in frame['action'] + frame['raw_action'] + frame['agent'] +
                        frame['object'] + [frame['angle'], frame['coverage']]) or not 0 <= frame['coverage'] <= 1):
                raise ValueError('Traza incompatible')


def evaluate_condition(model, task_factory, run, contract, out, pause, device):
    """Guarda por grupos completos y acepta reanudación solo con el mismo contrato."""
    out = Path(out)
    partial = Path(str(out) + '.partial')
    if out.exists():
        result = json.loads(out.read_text(encoding='utf-8'))
        if result['contract'] != contract:
            raise ValueError(f'Resultado incompatible: {out}')
        records = result['records']
        check_records(records, contract)
        if len(records) != contract['episodes'] or result['successes'] != sum(r['success'] for r in records):
            raise ValueError(f'Conteo incompatible: {out}')
        print('Reutilizado', out.name, flush=True)
        return True
    records, times, clipped, components = [], [], 0, 0
    if partial.exists():
        saved = json.loads(partial.read_text(encoding='utf-8'))
        if saved['contract'] != contract:
            raise ValueError(f'Parcial incompatible: {partial}')
        records, times = saved['records'], saved['times']
        clipped, components = saved['clipped'], saved['components']
        check_records(records, contract)
        if len(records) % contract['batch']:
            raise ValueError('El parcial no termina en una frontera de lote')
    started = time.perf_counter()
    while len(records) < contract['episodes']:
        start = contract['eval_seed'] + len(records)
        count = min(contract['batch'], contract['episodes'] - len(records))
        seeds = list(range(start, start + count))
        group, elapsed, clip, total = run(model, task_factory, seeds, contract['goal'], contract['second_goal'],
                                         contract['instruction'], device, contract['max_steps'], False)
        if [r['seed'] for r in group] != seeds or len(group) != count:
            raise ValueError('Grupo de escenas incompatible')
        records.extend(group)
        times.extend(elapsed)
        clipped += clip
        components += total
        check_records(records, contract)
        atomic_json(partial, {'contract': contract, 'records': records, 'times': times,
                              'clipped': clipped, 'components': components})
        memory = psutil.Process().memory_info()
        print('Escenas completadas', out.name, len(records), '/', contract['episodes'],
              'compromiso_pico', getattr(memory, 'peak_pagefile', None),
              'cuda_reservada_pico', torch.cuda.max_memory_reserved(device) if device.type == 'cuda' else None,
              flush=True)
        if pause.exists():
            pause.unlink()
            print('Pausa segura tras grupo', flush=True)
            return False
    k = sum(r['success'] for r in records)
    lo, hi = wilson(k, len(records))
    result = {'contract': contract, 'successes': k, 'episodes': len(records),
              'wilson95': [max(0., lo), min(1., hi)],
              'batch_inference_ms_median': float(np.median(times) * 1000),
              'fraction_clipped_components': clipped / components,
              'wall_seconds_this_run': time.perf_counter() - started,
              'cuda_peak_allocated_bytes_this_run': torch.cuda.max_memory_allocated(device) if device.type == 'cuda' else None,
              'cuda_peak_reserved_bytes_this_run': torch.cuda.max_memory_reserved(device) if device.type == 'cuda' else None,
              'records': records}
    atomic_json(out, result)
    partial.unlink()
    print('Finalizado', out.name, flush=True)
    return True


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--blue', required=True)
    p.add_argument('--orange', required=True)
    p.add_argument('--base', required=True)
    p.add_argument('--backbone', required=True)
    p.add_argument('--checkpoint', required=True)
    p.add_argument('--protocol', required=True)
    p.add_argument('--diagnostic-reference', required=True)
    p.add_argument('--out', required=True)
    a = p.parse_args()
    plan = json.loads(Path(a.protocol).read_text(encoding='utf-8'))
    if plan['format'] != 'oryon-p13-l09-actor-batch4-v1':
        raise ValueError('Protocolo desconocido')
    if (plan['batch'] != 4 or plan['episodes'] != 100 or plan['eval_seed'] != 70000 or
        plan['device_type'] != 'cuda' or plan['autocast'] is not False or plan['max_steps'] is not None or
        plan['model_order'] != ['base', 'lora'] or plan['cases'] != CASES or
        plan['horizon'] != 16 or plan['execute'] != 8 or plan['noise_dimensions'] != 32 or
        plan['image_shape'] != [96, 96, 3] or plan['state_dimensions'] != 2 or
        plan['action_dimensions'] != 2 or plan['action_unit'] != 'mm' or
        plan['action_clip_mm'] != [0, 512] or plan['rng'] != 'separate_generator_per_scene' or
        plan['instruction_protocol'] != 'fixed_for_episode' or
        plan['chunk_transition'] != 'finish_pending_before_replanning' or
        str(torch.__version__) != plan['torch']):
        raise ValueError('Protocolo de producción incompatible')
    if any(version(package) != expected for package, expected in plan['packages'].items()):
        raise ValueError('Versiones de dependencias incompatibles')
    for path, digest in plan['source_sha256'].items():
        if sha(path) != digest:
            raise ValueError(f'Código incompatible: {path}')
    base_hash, checkpoint_hash = sha(Path(a.base) / 'model.safetensors'), sha(a.checkpoint)
    if (base_hash != plan['base_sha256'] or checkpoint_hash != plan['lora_sha256'] or
        sha(Path(a.checkpoint).with_suffix('.json')) != plan['lora_metadata_sha256']):
        raise ValueError('Pesos incompatibles')
    groups = []
    for path in (a.blue, a.orange):
        info, episodes = load_episodes(path, 'observation.image')
        lo, hi = map(int, info['splits']['train'].split(':'))
        groups.append(episodes[lo:hi])
    stats = training_stats(groups)
    trained = load_trained_checkpoint(a.checkpoint)
    c = trained['contract']
    datasets = dataset_fingerprints([a.blue, a.orange])
    configs = config_fingerprints(a.base, a.backbone)
    if (c['base_sha256'] != base_hash or c['rank'] != plan['rank'] or c['alpha'] != plan['alpha'] or
        not matching_fingerprints(c['datasets'], datasets) or not matching_fingerprints(c['config_fingerprints'], configs)):
        raise ValueError('Datos, procesador o ajuste incompatibles')
    for key in stats:
        for measure in stats[key]:
            if not np.array_equal(stats[key][measure], trained['stats'][key][measure]):
                raise ValueError('Estadísticas distintas')
    device = torch.device(plan['device_type'])
    torch.cuda.reset_peak_memory_stats(device)
    model, names, heads = construct(a.base, a.backbone, stats, plan['rank'], plan['alpha'])
    if (model.config.chunk_size != plan['horizon'] or model.config.n_action_steps != plan['execute'] or
        model.config.max_action_dim != plan['noise_dimensions'] or model.config.max_state_dim != 32):
        raise ValueError('Horizontes o dimensiones del actor incompatibles')
    if names != c['lora_targets'] or heads != tuple(c['trainable_heads']):
        raise ValueError('Adaptadores incompatibles')
    params = {name: param for name, param in model.named_parameters() if param.requires_grad}
    if set(params) != set(trained['trainable']):
        raise ValueError('Pesos entrenables incompatibles')
    if any(torch.count_nonzero(param).item() for name, param in params.items() if name.endswith('.b')):
        raise ValueError('La base debe iniciar con contribución LoRA nula')
    model = model.to(device).eval()
    params = {name: param for name, param in model.named_parameters() if param.requires_grad}
    if set(params) != set(trained['trainable']):
        raise ValueError('Pesos entrenables distintos tras mover el modelo')
    outdir = Path(a.out)
    outdir.mkdir(parents=True, exist_ok=True)
    pause = outdir / 'suite.pause'
    reference_path = Path(a.diagnostic_reference)
    if sha(reference_path) != plan['diagnostic_reference_sha256']:
        raise ValueError('Referencia diagnóstica incompatible')
    reference = json.loads(reference_path.read_text(encoding='utf-8'))
    ref_contract = reference['contract']
    if (ref_contract['checkpoint_sha256'] != checkpoint_hash or ref_contract['batch'] != 4 or
        ref_contract['eval_seed'] != 60000 or ref_contract['episodes'] != 4 or ref_contract['max_steps'] != 24 or
        ref_contract['goal'] != 'azul' or ref_contract['second_goal'] is not None or
        ref_contract['instruction'] != CASES[0]['instruction'] or ref_contract['device_type'] != device.type or
        ref_contract['torch'] != torch.__version__ or ref_contract['autocast'] is not False or
        ref_contract['trace_version'] != 2 or not ref_contract['record_noise_hash']):
        raise ValueError('Contrato de referencia diagnóstica incompatible')
    base_parameters = {name: param.detach().cpu().clone() for name, param in params.items()}
    diagnostic_seeds = [60000, 60001, 60002, 60003]
    base_before, _, _, _ = run_group(model, LanguageTask, diagnostic_seeds, 'azul', None,
                                      CASES[0]['instruction'], device, 24, True)
    with torch.no_grad():
        for name, param in params.items():
            param.copy_(trained['trainable'][name])
    diagnostic, _, _, _ = run_group(model, LanguageTask, diagnostic_seeds, 'azul', None,
                                    CASES[0]['instruction'], device, 24, True)
    if diagnostic != reference['records']:
        raise ValueError('La ruta de lote difiere de la referencia diagnóstica; no se abrió la reserva')
    with torch.no_grad():
        for name, param in params.items():
            param.copy_(base_parameters[name])
    del base_parameters
    base_after, _, _, _ = run_group(model, LanguageTask, diagnostic_seeds, 'azul', None,
                                     CASES[0]['instruction'], device, 24, True)
    if base_before != base_after:
        raise ValueError('La restauración de la base altera el diagnóstico; no se abrió la reserva')
    atomic_json(outdir / 'preflight.json', {'reference_sha256': plan['diagnostic_reference_sha256'],
                 'checkpoint_sha256': checkpoint_hash, 'protocol_sha256': sha(a.protocol),
                 'seeds': diagnostic_seeds, 'steps': 24, 'records_exact': True,
                 'base_restoration_records_exact': True})
    print('Preflight fuera de reserva: referencia y restauración de base exactas', flush=True)
    for policy in plan['model_order']:
        if policy == 'lora':
            with torch.no_grad():
                for name, param in params.items():
                    param.copy_(trained['trainable'][name])
        for case in plan['cases']:
            contract = {'base_sha256': base_hash, 'checkpoint_sha256': None if policy == 'base' else checkpoint_hash,
                        'protocol_sha256': sha(a.protocol),
                        'datasets': datasets, 'config_fingerprints': configs,
                        'goal': case['goal'], 'second_goal': case['second_goal'], 'instruction': case['instruction'],
                        'instruction_protocol': 'fixed_for_episode',
                        'chunk_transition': 'finish_pending_before_replanning',
                        'episodes': plan['episodes'], 'eval_seed': plan['eval_seed'], 'max_steps': plan['max_steps'],
                        'trace_version': 2, 'record_noise_hash': False, 'autocast': plan['autocast'],
                        'device_type': device.type, 'torch': torch.__version__, 'rank': plan['rank'], 'alpha': plan['alpha'],
                        'batch': plan['batch'], 'rng': 'separate_generator_per_scene'}
            if not evaluate_condition(model, LanguageTask, run_group, contract,
                                      outdir / f"{policy}-{case['name']}.json", pause, device):
                return


if __name__ == '__main__':
    main()
