"""Figures of an analysis folder (analysis spec 3.7). Agg backend, no timestamps in the files, every figure closed."""
from __future__ import annotations

from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402
from scipy.cluster.hierarchy import dendrogram  # noqa: E402

from .metrics import METRIC_LABELS  # noqa: E402
from .split import HEMIS, LAYERS  # noqa: E402

EXPLORATORY = "EXPLORATORY — not a group test"


def _save(fig, out_dir, name: str, formats) -> list:
    out_dir = Path(out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)
    paths = []
    for fmt in formats:
        p = out_dir / f"{name}.{fmt}"
        fig.savefig(p, format=fmt, dpi=110, metadata={"Date": None} if fmt == "svg" else None)
        paths.append(p)
    plt.close(fig)
    return paths


def _cell_title(layer, hemi):
    return f"{'L2/3' if layer == 'L2' else layer} · {'left' if hemi == 'L' else 'right'}"


def fig_subject_strips(somas: pd.DataFrame, metric: str, out_dir, formats, analysis_id: str, seed: int = 0) -> list:
    rng = np.random.default_rng(seed)
    animals = sorted(somas["animal"].astype(str).unique()) if len(somas) else []
    fig, axes = plt.subplots(2, 2, figsize=(max(6, 1.2 * len(animals) + 3), 7), layout="constrained", sharey=True)
    for ax, (layer, hemi) in zip(axes.ravel(), [(l, h) for l in LAYERS for h in HEMIS]):
        cell = somas[(somas["layer"] == layer) & (somas["hemisphere"] == hemi)] if len(somas) else somas
        data, pos = [], []
        for i, a in enumerate(animals):
            v = pd.to_numeric(cell.loc[cell["animal"].astype(str) == a, metric], errors="coerce").dropna().to_numpy()
            if len(v):
                data.append(v); pos.append(i)
                ax.scatter(i + rng.uniform(-0.18, 0.18, len(v)), v, s=9, alpha=0.5, color="#4a6fa5", linewidths=0)
        if data:
            ax.boxplot(data, positions=pos, widths=0.5, showfliers=False, medianprops={"color": "#c0392b"})
        else:
            ax.text(0.5, 0.5, "no somas", ha="center", va="center", transform=ax.transAxes, color="#888")
        ax.set_title(_cell_title(layer, hemi))
        ax.set_xticks(range(len(animals)))
        ax.set_xticklabels(animals, rotation=45, ha="right")
        ax.set_xlim(-0.7, max(len(animals) - 0.3, 0.7))
    axes[0, 0].set_ylabel(METRIC_LABELS.get(metric, metric)); axes[1, 0].set_ylabel(METRIC_LABELS.get(metric, metric))
    fig.suptitle(f"{METRIC_LABELS.get(metric, metric)} per subject — {analysis_id}")
    return _save(fig, out_dir, f"subjects_{metric}", formats)


def fig_subject_heatmap(subjects: pd.DataFrame, metric: str, out_dir, formats, analysis_id: str) -> list:
    cells = [f"{l}_{h}" for l in LAYERS for h in HEMIS]
    animals = sorted(subjects["animal"].astype(str).unique()) if len(subjects) else []
    m = np.full((len(animals), len(cells)), np.nan)
    for _, r in subjects.iterrows():
        key = f"{r['layer']}_{r['hemisphere']}"
        if key in cells and str(r["animal"]) in animals:
            m[animals.index(str(r["animal"])), cells.index(key)] = float(r[f"{metric}_mean"])
    fig, ax = plt.subplots(figsize=(6, max(3, 0.4 * len(animals) + 1.5)), layout="constrained")
    cmap = matplotlib.colormaps["viridis"].with_extremes(bad="#eeeeee")      # set_bad is deprecated in matplotlib 3.11
    im = ax.imshow(np.ma.masked_invalid(m), aspect="auto", cmap=cmap)
    ax.set_xticks(range(len(cells))); ax.set_xticklabels([_cell_title(*c.split("_")) for c in cells], rotation=30, ha="right")
    ax.set_yticks(range(len(animals))); ax.set_yticklabels(animals)
    for i in range(len(animals)):
        for j in range(len(cells)):
            if not np.isnan(m[i, j]):
                ax.text(j, i, f"{m[i, j]:.3g}", ha="center", va="center", fontsize=7, color="white")
    fig.colorbar(im, ax=ax, label=f"mean {METRIC_LABELS.get(metric, metric)}")
    ax.set_title(f"Subject × layer × hemisphere mean — {analysis_id}")
    return _save(fig, out_dir, f"heatmap_{metric}", formats)


def fig_qc(qc: pd.DataFrame, out_dir, formats, analysis_id: str) -> list:
    fig, ax = plt.subplots(figsize=(max(6, 0.25 * len(qc) + 2), 4), layout="constrained")
    x = np.arange(len(qc))
    ax.bar(x, qc["n_kept"], color="#4a6fa5", label="kept")
    ax.bar(x, qc["n_dropped"], bottom=qc["n_kept"], color="#c0392b", label="dropped")
    ax.set_xticks(x); ax.set_xticklabels(qc["stack"].astype(str), rotation=90, fontsize=6)
    ax.set_ylabel("somas"); ax.legend(loc="upper right")
    ax.set_title(f"Somas kept / dropped per stack — {analysis_id}")
    return _save(fig, out_dir, "qc_somas", formats)


def fig_pca(split, out_dir, formats, analysis_id: str) -> list:
    a = split.assignments
    fig, ax = plt.subplots(figsize=(6, 5), layout="constrained")
    colors = ["#4a6fa5", "#e08e2b", "#5aa469", "#c0392b", "#8e6bb3"]
    for lab in sorted(a["kmeans"].unique()):
        sel = a[a["kmeans"] == lab]
        ax.scatter(sel["pc1"], sel["pc2"], s=60, color=colors[int(lab) % len(colors)], label=f"k-means cluster {lab}")
    for _, r in a.iterrows():
        ax.annotate(str(r["animal"]), (r["pc1"], r["pc2"]), xytext=(4, 4), textcoords="offset points", fontsize=8)
    ax.set_xlabel("PC1"); ax.set_ylabel("PC2"); ax.legend()
    ax.set_title(f"{EXPLORATORY}\nsubjects in metric space — {analysis_id}", fontsize=10)
    return _save(fig, out_dir, "split_pca", formats)


def fig_dendrogram(split, out_dir, formats, analysis_id: str) -> list:
    fig, ax = plt.subplots(figsize=(max(5, 0.5 * len(split.features) + 2), 4), layout="constrained")
    dendrogram(split.linkage, labels=list(split.features.index), ax=ax, color_threshold=0, above_threshold_color="#4a6fa5")
    ax.set_ylabel("ward distance (z-scored profile)")
    ax.set_title(f"{EXPLORATORY}\nhierarchical clustering of subjects — {analysis_id}", fontsize=10)
    return _save(fig, out_dir, "split_dendrogram", formats)


def fig_stability(split, out_dir, formats, analysis_id: str) -> list:
    st = split.stability
    fig, ax = plt.subplots(figsize=(max(4, 0.45 * len(st) + 2), max(3.5, 0.45 * len(st) + 1.5)), layout="constrained")
    im = ax.imshow(st.to_numpy(), vmin=0, vmax=1, cmap="Blues")
    ax.set_xticks(range(len(st))); ax.set_xticklabels(list(st.columns), rotation=90)
    ax.set_yticks(range(len(st))); ax.set_yticklabels(list(st.index))
    fig.colorbar(im, ax=ax, label="bootstrap co-assignment")
    ax.set_title(f"{EXPLORATORY}\nhow often two subjects share a cluster — {analysis_id}", fontsize=10)
    return _save(fig, out_dir, "split_stability", formats)


def make_all(somas, subjects, qc, split, metrics, out_dir, formats, analysis_id: str):
    out_dir = Path(out_dir)
    jobs = []                                   # figures that need data are skipped when there is none
    for m in metrics:
        if len(somas):
            jobs.append((f"subjects_{m}", lambda m=m: fig_subject_strips(somas, m, out_dir, formats, analysis_id)))
        if len(subjects):
            jobs.append((f"heatmap_{m}", lambda m=m: fig_subject_heatmap(subjects, m, out_dir, formats, analysis_id)))
    if len(qc):
        jobs.append(("qc_somas", lambda: fig_qc(qc, out_dir, formats, analysis_id)))
    if split is not None and split.skipped_reason is None:
        jobs += [("split_pca", lambda: fig_pca(split, out_dir, formats, analysis_id)),
                 ("split_dendrogram", lambda: fig_dendrogram(split, out_dir, formats, analysis_id)),
                 ("split_stability", lambda: fig_stability(split, out_dir, formats, analysis_id))]
    files, errors = {}, {}
    for name, job in jobs:
        try:
            files[name] = [p.name for p in job()]
        except Exception as e:           # one broken figure must not lose the others
            plt.close("all")
            errors[name] = f"{type(e).__name__}: {e}"
    return files, errors
