"""Atomic artifacts, reproducibility fingerprints and canonical prediction keys."""
from __future__ import annotations

import hashlib
import json
import os
from pathlib import Path
import platform
import random
import tempfile

import numpy as np
import pandas as pd
import joblib
import scipy
import sklearn
import torch


def safe_json(value):
    if isinstance(value, dict):
        return {str(k): safe_json(v) for k, v in value.items()}
    if isinstance(value, (tuple, list, np.ndarray)):
        return [safe_json(v) for v in value]
    if isinstance(value, np.generic):
        return safe_json(value.item())
    if isinstance(value, float) and not np.isfinite(value):
        return None
    if value is pd.NA:
        return None
    if isinstance(value, Path):
        return str(value)
    if isinstance(value, torch.Tensor):
        return safe_json(value.detach().cpu().numpy())
    return value


def json_hash(value):
    return hashlib.sha256(json.dumps(safe_json(value), sort_keys=True, separators=(',', ':'),
                                     allow_nan=False).encode()).hexdigest()


def _atomic(path, writer):
    path = Path(path)
    path.parent.mkdir(parents=True, exist_ok=True)
    fd, temporary = tempfile.mkstemp(prefix=path.name + '.', suffix='.tmp', dir=path.parent)
    os.close(fd)
    try:
        writer(Path(temporary))
        os.replace(temporary, path)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def atomic_json(path, value):
    _atomic(path, lambda temp: temp.write_text(json.dumps(safe_json(value), indent=2, sort_keys=True,
                                                        allow_nan=False) + '\n', encoding='utf-8'))


def atomic_csv(path, frame):
    _atomic(path, lambda temp: frame.to_csv(temp, index=False, float_format='%.12g', na_rep=''))


def atomic_torch(path, value):
    _atomic(path, lambda temp: torch.save(value, temp))


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


def code_hashes(root=None):
    root = Path(root or Path(__file__).resolve().parent)
    return {str(path.relative_to(root)): file_hash(path) for path in sorted(root.rglob('*'))
            if path.is_file() and path.suffix in ('.py', '.sh') and '__pycache__' not in path.parts}


def versions():
    return dict(python=platform.python_version(), torch=str(torch.__version__), numpy=np.__version__,
                pandas=pd.__version__, sklearn=sklearn.__version__, scipy=scipy.__version__,
                joblib=joblib.__version__, platform=platform.platform(),
                machine=platform.machine(), cuda=torch.version.cuda,
                cuda_available=torch.cuda.is_available())


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 score_frame(table, fold, scores=None):
    frame = 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))
    if hasattr(table, 'committee'):
        frame['committee'] = table.committee
    if scores is not None:
        if not isinstance(scores, dict):
            raise TypeError('scores must map score column names to one-dimensional arrays')
        for name, value in scores.items():
            value = np.asarray(value, float)
            if value.shape != (len(frame),) or not np.isfinite(value).all() or ((value < 0) | (value > 1)).any():
                raise ValueError(f'Invalid canonical score vector: {name}')
            frame[name] = value
    return frame


def faculty_support(table, faculties=None):
    """Show every requested faculty, including absent target rows without dummy predictions."""
    records = []
    for faculty in faculties or table.faculty_names:
        fi = table.faculty_names.index(faculty)
        mask = table.faculty == fi
        rows, positives = int(mask.sum()), int(table.y[mask].sum())
        records.append(dict(faculty=faculty, rows=rows, positives=positives, negatives=rows - positives,
                            students=int(len(np.unique(table.student[mask])))))
    return pd.DataFrame(records, columns=['faculty', 'rows', 'positives', 'negatives', 'students'])


def print_table(title, frame):
    print(f'\n{title} ({len(frame):,} rows)', flush=True)
    if frame.empty:
        print('Columns: ' + ', '.join(map(str, frame.columns)) + '; no supported rows.', flush=True)
    else:
        with pd.option_context('display.max_rows', None, 'display.max_columns', None,
                               'display.max_colwidth', None, 'display.width', 240):
            print(frame.to_string(index=False, max_rows=None, max_cols=None,
                                  float_format=lambda number: f'{number:.8g}'), flush=True)
