"""Shared inference, checkpoint, and provenance helpers."""
from __future__ import annotations

import hashlib
import json
import os
from pathlib import Path
import random
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader


def seed_all(seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True


def clean_json(value):
    if isinstance(value, dict):
        return {str(k): clean_json(v) for k, v in value.items()}
    if isinstance(value, (tuple, list)):
        return [clean_json(v) for v in value]
    if isinstance(value, np.ndarray):
        return clean_json(value.tolist())
    if isinstance(value, np.generic):
        return clean_json(value.item())
    if isinstance(value, float) and not np.isfinite(value):
        return None
    if isinstance(value, Path):
        return str(value)
    return value


def atomic_json(value, path):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    temp = path.with_name(path.name + '.tmp')
    temp.write_text(json.dumps(clean_json(value), indent=2, sort_keys=True, allow_nan=False) + '\n')
    os.replace(temp, path)


def atomic_checkpoint(value, path):
    path = Path(path)
    temp = path.with_name(path.name + '.tmp')
    torch.save(value, temp)
    os.replace(temp, path)


def sha256(path):
    digest = hashlib.sha256()
    with open(path, 'rb') as f:
        for block in iter(lambda: f.read(8 * 1024 * 1024), b''):
            digest.update(block)
    return digest.hexdigest()


def to_device(batch, device):
    return {k: v.to(device, non_blocking=True) for k, v in batch.items()}


@torch.no_grad()
def infer(model, dataset, device, batch_size=128, intervention=None, diagnostics=False):
    model.eval()
    scores, parts = [], []
    loader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0,
                        pin_memory=str(device).startswith('cuda'))
    for host in loader:
        batch = to_device(host, device)
        out = model(batch, intervention=intervention)
        scores.append(out['prob'].cpu().numpy())
        if diagnostics:
            a = out['attention']
            mask = batch['h_mask'].to(a.dtype)
            known = batch['h_grade_present'] * mask
            grade_mass = (a * known).sum(-1)
            d = {k: out[k].cpu().numpy() for k in ['route_entropy', 'memory_shift_abs', 'static_shift_abs', 'gap_shift_abs', 'gap_score']}
            d.update(readiness_mean=out['readiness'].mean(-1).cpu().numpy(),
                     requirement_mean=out['requirement'].mean(-1).cpu().numpy(),
                     attention_failure=(a * batch['h_y']).sum(-1).cpu().numpy(),
                     attention_recency=(a * batch['h_recency']).sum(-1).cpu().numpy(),
                     attention_grade=torch.where(grade_mass > 0, (a * batch['h_grade'] * known).sum(-1) / grade_mass.clamp_min(1e-12), torch.full_like(grade_mass, float('nan'))).cpu().numpy(),
                     attention_same_course=(a * batch['h_same']).sum(-1).cpu().numpy(),
                     attention_entropy=(-(a * torch.log(a.clamp_min(1e-12))).sum(-1)).cpu().numpy())
            parts.append(pd.DataFrame(d))
    return np.concatenate(scores) if scores else np.empty(0), pd.concat(parts, ignore_index=True) if parts else pd.DataFrame()


def score_frame(table, fold):
    return pd.DataFrame(dict(fold=int(fold), faculty=[table.faculty_names[int(i)] for i in table.faculty],
                             sample_id=table.sample_id, student_id=table.student, course_id=table.course,
                             semester=table.semester,
                             target_NHHK=(table.semester // 3) * 10 + (table.semester % 3) + 1,
                             actual=table.y, committee=table.committee))
