"""Estado reanudable y huellas del conjunto para campañas de entrenamiento."""
import hashlib
import random
from pathlib import Path
import numpy as np
import torch


def dataset_fingerprints(paths):
    result = {}
    for path in paths:
        root = Path(path).resolve()
        files = sorted(p for p in root.rglob('*') if p.is_file() and
                       (p.suffix == '.parquet' or p.name in ('info.json', 'atlas_procedencia.jsonl')))
        if not files: raise ValueError(f'Sin datos en {root}')
        for file in files:
            h = hashlib.sha256()
            with file.open('rb') as f:
                for block in iter(lambda: f.read(1024 * 1024), b''): h.update(block)
            result[str(file)] = h.hexdigest()
    return result


def save_resume(path, *, completed, contract, model, optimizer, rng, device, ema=None):
    state = {'completed': completed, 'contract': contract, 'model': model.state_dict(),
             'optimizer': optimizer.state_dict(), 'numpy_rng': rng.bit_generator.state,
             'python_rng': random.getstate(), 'torch_rng': torch.get_rng_state(),
             'cuda_rng': torch.cuda.get_rng_state(device) if device.type == 'cuda' else None,
             'ema': None if ema is None else ema.model.state_dict()}
    target = Path(path); temp = target.with_suffix(target.suffix + '.tmp')
    torch.save(state, temp)
    temp.replace(target)


def restore_resume(path, *, contract, model, optimizer, rng, device, ema=None):
    state = torch.load(path, map_location=device, weights_only=False)
    if state['contract'] != contract: raise ValueError('El contrato de la ejecución no coincide')
    model.load_state_dict(state['model']); optimizer.load_state_dict(state['optimizer'])
    rng.bit_generator.state = state['numpy_rng']; random.setstate(state['python_rng'])
    torch.set_rng_state(state['torch_rng'].cpu())
    if device.type == 'cuda': torch.cuda.set_rng_state(state['cuda_rng'].cpu(), device)
    if (ema is None) != (state['ema'] is None): raise ValueError('Estado EMA incompatible')
    if ema is not None: ema.model.load_state_dict(state['ema'])
    return int(state['completed'])
