"""Group comparison (groups spec, 2026-10-14). The subjects key gives each rat a blinded group (A/B) and a preferred
paw; the contralateral hemisphere is the one opposite the paw (right paw -> left hemisphere). Per rat and layer the
contralateral and ipsilateral pooled means of every metric give contra - ipsi; then, per metric and layer:
  contra-ipsi: A vs B                    Mann-Whitney, permutation of the group labels, bootstrap CI of the mean difference
  contra vs ipsi within A / within B     paired Wilcoxon on the per-rat difference, bootstrap CI of its mean
  overall: A vs B                        rat means over both hemispheres, Mann-Whitney + permutation + CI
  the same three by paw                  right- vs left-pawed
Nothing here unblinds: A and B are reported as given."""
from __future__ import annotations

from dataclasses import dataclass
from typing import Optional

import numpy as np
import pandas as pd
from scipy import stats

from .aggregate import SUBJECT_KEYS

BY_RAT_COLUMNS = ("animal", "group", "paw", "layer", "metric", "contra_hemisphere", "contra_mean", "ipsi_mean", "diff",
                  "n_somas_contra", "n_somas_ipsi", "overall_mean", "n_somas")
TEST_COLUMNS = ("metric", "layer", "comparison", "label_1", "label_2", "n_1", "n_2", "mean_1", "mean_2", "estimate", "ci_low", "ci_high",
                "test", "p_test", "p_permutation")
NO_LABELS = "no group or paw labels in the inputs (import the subjects key)"


@dataclass
class GroupsResult:
    skipped_reason: Optional[str] = None
    by_rat: Optional[pd.DataFrame] = None
    tests: Optional[pd.DataFrame] = None


def contra_hemisphere(paw) -> Optional[str]:
    p = str(paw or "").strip().lower()
    return {"right": "L", "left": "R"}.get(p)


def _labels(somas: pd.DataFrame) -> pd.DataFrame:
    g = somas.groupby("animal", sort=True)
    out = pd.DataFrame({"group": g["group"].first() if "group" in somas.columns else "", "paw": g["paw"].first() if "paw" in somas.columns else ""})
    out = out.fillna("").astype(str)
    out["contra"] = out["paw"].map(contra_hemisphere)
    return out


def by_rat_table(somas: pd.DataFrame, metrics) -> pd.DataFrame:
    labels = _labels(somas)
    cell = somas.groupby(SUBJECT_KEYS, sort=True)
    rows = []
    for m in metrics:
        v = pd.to_numeric(somas[m], errors="coerce")
        mean = v.groupby([somas["animal"], somas["layer"], somas["hemisphere"]]).mean()
        n = v.groupby([somas["animal"], somas["layer"], somas["hemisphere"]]).count()
        lmean = v.groupby([somas["animal"], somas["layer"]]).mean(); ln = v.groupby([somas["animal"], somas["layer"]]).count()
        for (animal, layer), om in lmean.items():
            lab = labels.loc[animal]
            c = lab["contra"]; i = {"L": "R", "R": "L"}.get(c)
            cm = mean.get((animal, layer, c), np.nan) if c else np.nan
            im = mean.get((animal, layer, i), np.nan) if i else np.nan
            rows.append({"animal": animal, "group": lab["group"], "paw": lab["paw"], "layer": layer, "metric": m, "contra_hemisphere": c or "",
                         "contra_mean": cm, "ipsi_mean": im, "diff": cm - im, "n_somas_contra": int(n.get((animal, layer, c), 0)) if c else 0,
                         "n_somas_ipsi": int(n.get((animal, layer, i), 0)) if i else 0, "overall_mean": om, "n_somas": int(ln[(animal, layer)])})
    return pd.DataFrame(rows, columns=list(BY_RAT_COLUMNS))


def _boot_ci(x, rng, n=2000):
    x = np.asarray(x, float)
    if len(x) < 2:
        return np.nan, np.nan
    b = np.array([rng.choice(x, len(x)).mean() for _ in range(n)])
    return float(np.percentile(b, 2.5)), float(np.percentile(b, 97.5))


def _boot_ci_diff(a, b, rng, n=2000):
    a, b = np.asarray(a, float), np.asarray(b, float)
    if len(a) < 2 or len(b) < 2:
        return np.nan, np.nan
    d = np.array([rng.choice(a, len(a)).mean() - rng.choice(b, len(b)).mean() for _ in range(n)])
    return float(np.percentile(d, 2.5)), float(np.percentile(d, 97.5))


def _perm_p(a, b, rng, n):
    a, b = np.asarray(a, float), np.asarray(b, float)
    if len(a) < 2 or len(b) < 2 or n <= 0:
        return np.nan
    obs = a.mean() - b.mean(); pooled = np.concatenate([a, b]); na = len(a)
    cnt = 0
    for _ in range(n):
        p = rng.permutation(pooled)
        if abs(p[:na].mean() - p[na:].mean()) >= abs(obs) - 1e-12:
            cnt += 1
    return float((cnt + 1) / (n + 1))


def _two_sample(metric, layer, comparison, l1, l2, a, b, rng, n_perm):
    a, b = np.asarray(a, float), np.asarray(b, float)
    a, b = a[np.isfinite(a)], b[np.isfinite(b)]
    p = stats.mannwhitneyu(a, b).pvalue if len(a) >= 1 and len(b) >= 1 and (len(a) + len(b)) > 2 else np.nan
    lo, hi = _boot_ci_diff(a, b, rng)
    return {"metric": metric, "layer": layer, "comparison": comparison, "label_1": l1, "label_2": l2, "n_1": len(a), "n_2": len(b),
            "mean_1": a.mean() if len(a) else np.nan, "mean_2": b.mean() if len(b) else np.nan,
            "estimate": (a.mean() - b.mean()) if len(a) and len(b) else np.nan, "ci_low": lo, "ci_high": hi, "test": "mann-whitney",
            "p_test": p, "p_permutation": _perm_p(a, b, rng, n_perm)}


def _paired(metric, layer, comparison, label, diffs, rng):
    d = np.asarray(diffs, float); d = d[np.isfinite(d)]
    p = stats.wilcoxon(d).pvalue if len(d) >= 2 and np.any(d != 0) else np.nan
    lo, hi = _boot_ci(d, rng)
    return {"metric": metric, "layer": layer, "comparison": comparison, "label_1": f"{label} contra", "label_2": f"{label} ipsi", "n_1": len(d), "n_2": len(d),
            "mean_1": np.nan, "mean_2": np.nan, "estimate": d.mean() if len(d) else np.nan, "ci_low": lo, "ci_high": hi, "test": "wilcoxon (paired)",
            "p_test": p, "p_permutation": np.nan}


def run_groups(somas_kept: pd.DataFrame, metrics, params) -> GroupsResult:
    gp = params.groups
    if not gp.enabled:
        return GroupsResult(skipped_reason="groups.enabled is false")
    if len(somas_kept) == 0 or not ({"group", "paw"} & set(somas_kept.columns)):
        return GroupsResult(skipped_reason=NO_LABELS)
    labels = _labels(somas_kept)
    if not (labels["group"].astype(bool).any() or labels["paw"].astype(bool).any()):
        return GroupsResult(skipped_reason=NO_LABELS)
    by_rat = by_rat_table(somas_kept, metrics)
    rng = np.random.default_rng(gp.random_seed)
    tests = []
    for m in metrics:
        for layer in sorted(by_rat["layer"].unique()):
            t = by_rat[(by_rat.metric == m) & (by_rat.layer == layer)]
            for col, pairs, name in (("group", ("A", "B"), "A vs B"), ("paw", ("right", "left"), "right- vs left-pawed")):
                l1, l2 = pairs
                a, b = t[t[col] == l1], t[t[col] == l2]
                if len(a) and len(b):
                    tests.append(_two_sample(m, layer, f"contra-ipsi: {name}", l1, l2, a["diff"], b["diff"], rng, gp.n_permutations))
                    tests.append(_two_sample(m, layer, f"overall: {name}", l1, l2, a["overall_mean"], b["overall_mean"], rng, gp.n_permutations))
                for lab, g in ((l1, a), (l2, b)):
                    if len(g):
                        tests.append(_paired(m, layer, f"contra vs ipsi within {lab}" + ("-pawed" if col == "paw" else ""), lab, g["diff"], rng))
    return GroupsResult(None, by_rat, pd.DataFrame(tests, columns=list(TEST_COLUMNS)))
