"""EXPLORATORY unsupervised split of subjects (analysis spec 3.6). Groups (control vs stim) are unknown, so this
asks the data whether subjects fall into k profiles; it is not a group test. One feature vector per subject: the
subject x layer x hemisphere mean of every metric; missing cells imputed by the column mean and flagged."""
from __future__ import annotations

from dataclasses import dataclass
from typing import Optional

import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import linkage
from scipy.optimize import linear_sum_assignment
from sklearn.cluster import AgglomerativeClustering, KMeans
from sklearn.decomposition import PCA
from sklearn.metrics import silhouette_score

from .aggregate import SUBJECT_KEYS, by_subject

LAYERS = ("L2", "L5")
HEMIS = ("L", "R")


@dataclass
class SplitResult:
    skipped_reason: Optional[str] = None
    features: Optional[pd.DataFrame] = None
    assignments: Optional[pd.DataFrame] = None
    stability: Optional[pd.DataFrame] = None
    summary: Optional[pd.DataFrame] = None
    linkage: Optional[np.ndarray] = None


def feature_columns(metrics) -> list:
    return [f"{m}__{layer}_{hemi}_mean" for m in metrics for layer in LAYERS for hemi in HEMIS]


def features(subjects: pd.DataFrame, metrics) -> pd.DataFrame:
    cols = feature_columns(metrics)
    animals = sorted(subjects["animal"].astype(str).unique()) if len(subjects) else []
    raw = pd.DataFrame(np.nan, index=pd.Index(animals, name="animal"), columns=cols, dtype=float)
    for _, r in subjects.iterrows():
        for m in metrics:
            col = f"{m}__{r['layer']}_{r['hemisphere']}_mean"
            if col in raw.columns:
                raw.loc[str(r["animal"]), col] = float(r[f"{m}_mean"])
    flags = raw.isna()
    filled = raw.apply(lambda c: c.fillna(c.mean() if c.notna().any() else 0.0))
    for c in cols:
        filled[f"{c}_imputed"] = flags[c].to_numpy()
    return filled


def zscore(feats: pd.DataFrame, cols) -> pd.DataFrame:
    x = feats[list(cols)].astype(float)
    sd = x.std(ddof=0).replace(0.0, np.nan)
    return ((x - x.mean()) / sd).fillna(0.0)


def resample_within_cells(somas: pd.DataFrame, rng: np.random.Generator) -> pd.DataFrame:
    chosen = []
    for _, idx in somas.groupby(SUBJECT_KEYS, sort=True).indices.items():
        chosen.append(rng.choice(idx, size=len(idx), replace=True))
    order = np.concatenate(chosen) if chosen else np.array([], dtype=int)
    return somas.iloc[order].reset_index(drop=True)


def _kmeans(x: np.ndarray, k: int, seed: int) -> np.ndarray:
    return KMeans(n_clusters=k, random_state=seed, n_init=10).fit_predict(x)


def balanced_kmeans(x: np.ndarray, k: int, seed: int, max_iter: int = 100) -> np.ndarray:
    """k-means whose cluster sizes differ by at most 1: start from the seeded k-means centroids, then alternate an
    optimal size-capped assignment (Hungarian over n slots, cluster j owning n//k or n//k + 1 of them) with centroid
    updates until the labels stop changing."""
    n = len(x)
    km = KMeans(n_clusters=k, random_state=seed, n_init=10).fit(x)
    centers = km.cluster_centers_.copy()
    sizes = [n // k + (1 if j < n % k else 0) for j in range(k)]
    slot_cluster = np.repeat(np.arange(k), sizes)
    labels = np.full(n, -1)
    for _ in range(max_iter):
        d2 = ((x[:, None, :] - centers[None, :, :]) ** 2).sum(axis=2)        # n x k squared distances
        rows, cols = linear_sum_assignment(d2[:, slot_cluster])
        new = np.empty(n, dtype=int)
        new[rows] = slot_cluster[cols]
        if np.array_equal(new, labels):
            break
        labels = new
        for j in range(k):
            if (labels == j).any():
                centers[j] = x[labels == j].mean(axis=0)
    return labels


def _cluster(x: np.ndarray, k: int, seed: int, balanced: bool) -> np.ndarray:
    return balanced_kmeans(x, k, seed) if balanced else _kmeans(x, k, seed)


def _silhouette(x: np.ndarray, labels: np.ndarray) -> float:
    if 1 < len(set(labels.tolist())) < len(labels):
        return float(silhouette_score(x, labels))
    return float("nan")


def run_split(somas_kept: pd.DataFrame, metrics, params) -> SplitResult:
    sp = params.split
    metrics = list(metrics)
    subjects = by_subject(somas_kept, metrics)
    n = subjects["animal"].nunique() if len(subjects) else 0
    if n == 0:
        return SplitResult(skipped_reason=f"0 subjects, fewer than split.min_subjects = {sp.min_subjects}")
    feats = features(subjects, metrics)
    if not sp.enabled:
        return SplitResult(skipped_reason="split.enabled is false", features=feats)
    if n < sp.min_subjects:
        return SplitResult(skipped_reason=f"{n} subjects, fewer than split.min_subjects = {sp.min_subjects}", features=feats)
    cols = feature_columns(metrics)
    z = zscore(feats, cols)
    x = z.to_numpy(dtype=float)
    animals = list(z.index)
    k = min(sp.k, n)
    n_distinct = len(np.unique(x, axis=0))
    if n_distinct < k:                       # identical profiles would be split arbitrarily (and k-means warns)
        return SplitResult(skipped_reason=f"only {n_distinct} distinct subject profile{'s' if n_distinct != 1 else ''}, fewer than split.k = {k}",
                           features=feats)
    km = _cluster(x, k, sp.random_seed, sp.balanced)
    ward = AgglomerativeClustering(n_clusters=k, linkage="ward").fit_predict(x)
    n_pc = min(2, n, len(cols))
    pcs = PCA(n_components=n_pc, random_state=sp.random_seed).fit_transform(x)
    pc = np.zeros((n, 2))
    pc[:, :n_pc] = pcs
    # bootstrap: resample somas within every subject x layer x hemisphere cell, recompute the profile, re-cluster
    rng = np.random.default_rng(sp.random_seed)
    co = np.eye(n)
    if sp.n_bootstrap > 0:
        co = np.zeros((n, n))
        for b in range(sp.n_bootstrap):
            fb = features(by_subject(resample_within_cells(somas_kept, rng), metrics), metrics).reindex(animals)
            lab = _cluster(zscore(fb, cols).to_numpy(dtype=float), k, sp.random_seed + b + 1, sp.balanced)
            co += (lab[:, None] == lab[None, :])
        co /= sp.n_bootstrap
    stability = []       # mean co-assignment with the subject's k-means cluster mates; NaN for a singleton cluster or without bootstraps
    for i in range(n):
        same = [j for j in range(n) if j != i and km[j] == km[i]]
        stability.append(float(np.mean([co[i, j] for j in same])) if same and sp.n_bootstrap > 0 else float("nan"))
    assignments = pd.DataFrame({"animal": animals, "kmeans": km.astype(int), "ward": ward.astype(int), "pc1": pc[:, 0], "pc2": pc[:, 1],
                                "stability": stability})
    summary = pd.DataFrame({"method": ["kmeans", "ward"], "k": [k, k], "balanced": [bool(sp.balanced), False],
                            "silhouette": [_silhouette(x, km), _silhouette(x, ward)]})
    zf = z.copy()
    for c in cols:
        zf[f"{c}_imputed"] = feats[f"{c}_imputed"].to_numpy()
    return SplitResult(None, zf, assignments, pd.DataFrame(co, index=animals, columns=animals), summary,
                       linkage(x, method="ward") if n > 1 else None)
