#!/usr/bin/env python3
"""Infer each rat's dominant (trained) paw from an analysis folder by ASSUMING contralateral > ipsilateral in Layer 2:
the hemisphere with the higher Layer-2 pairs/µm² is contralateral to the trained paw, so the paw is the other side.
`--side-from max-slice` (default) lets the slice with the larger |L-R| decide; `pooled` uses both slices pooled.
Then run the comparisons that assumption makes possible, and the tDCS set-up: with the balanced clusters as the
stim/sham candidates, contra and ipsi levels and contra-ipsi per layer by cluster, bootstrap CIs and permutation p. The L2 contra-ipsi difference is positive by
construction and is reported only as a magnitude; every test below uses data not used to pick the side.
Writes <folder>/extra/inferred-paw/{inferred_paw.csv,tests.csv,README.md} and a copy of this script.
Usage: python3 scripts/inferred_paw_check.py <analysis folder> [--metric syn_per_um2]"""
from __future__ import annotations

import argparse
import shutil
import sys
from pathlib import Path

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

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from synapse_analysis import csvmeta  # noqa: E402


def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("folder"); ap.add_argument("--metric", default="syn_per_um2")
    ap.add_argument("--side-from", choices=("max-slice", "pooled"), default="max-slice")
    ap.add_argument("--bootstrap", type=int, default=2000); ap.add_argument("--seed", type=int, default=0)
    a = ap.parse_args()
    folder, m = Path(a.folder), a.metric
    somas, meta = csvmeta.read_csv(folder / "somas_filtered.csv")
    asg, _ = csvmeta.read_csv(folder / "split_assignments.csv")
    out = folder / "extra" / "inferred-paw"
    out.mkdir(parents=True, exist_ok=True)
    meta_out = dict(meta, table="")
    tests = []

    def test(name, **kw):
        tests.append({"test": name, **kw})
        print(f"{name}: " + ", ".join(f"{k}={v:.4g}" if isinstance(v, float) else f"{k}={v}" for k, v in kw.items()))

    # pooled-soma mean per animal x layer x hemisphere (all slices), and per slice
    cell = somas.groupby(["animal", "layer", "hemisphere"])[m].mean().unstack("hemisphere")
    L2 = cell.xs("L2", level="layer").dropna(subset=["L", "R"])
    L5 = cell.xs("L5", level="layer")
    per_slice = somas[somas.layer == "L2"].groupby(["animal", "slice", "hemisphere"])[m].mean().unstack("hemisphere").dropna()
    per_slice["diff"] = per_slice["L"] - per_slice["R"]
    rows = []
    for animal, r in L2.iterrows():
        if a.side_from == "max-slice" and animal in per_slice.index.get_level_values(0):
            ps = per_slice.loc[animal]
            best = ps["diff"].abs().idxmax()                     # the slice with the larger |L-R| decides
            contra, decided_by = ("L" if ps.loc[best, "diff"] > 0 else "R"), int(best)
        else:
            contra, decided_by = ("L" if r["L"] > r["R"] else "R"), 0
        paw = "right" if contra == "L" else "left"
        ipsi = "R" if contra == "L" else "L"
        l5 = L5.loc[animal] if animal in L5.index else None
        rows.append({"animal": animal, "inferred_paw": paw, "contra_hemisphere": contra, "decided_by_slice": decided_by,
                     "L2_contra": r[contra], "L2_ipsi": r[ipsi], "L2_contra_minus_ipsi": r[contra] - r[ipsi],
                     "L2_asymmetry_pct": 100 * (r[contra] - r[ipsi]) / r[[contra, ipsi]].mean(),
                     "L5_contra": l5[contra] if l5 is not None else np.nan, "L5_ipsi": l5[ipsi] if l5 is not None else np.nan,
                     "L5_contra_minus_ipsi": (l5[contra] - l5[ipsi]) if l5 is not None else np.nan})
    df = pd.DataFrame(rows).merge(asg[["animal", "kmeans", "stability"]].rename(columns={"kmeans": "balanced_cluster"}), on="animal", how="left")
    # per-slice L2 asymmetry: does the paw inferred from one slice hold in the other?
    sl = somas[somas.layer == "L2"].groupby(["animal", "slice", "hemisphere"])[m].mean().unstack("hemisphere")
    sl = (sl["L"] - sl["R"]).unstack("slice")
    df["L2_L_minus_R_slice1"] = df.animal.map(sl[1] if 1 in sl.columns else {})
    df["L2_L_minus_R_slice2"] = df.animal.map(sl[2] if 2 in sl.columns else {})
    both = df.dropna(subset=["L2_L_minus_R_slice1", "L2_L_minus_R_slice2"])
    have = df["L2_L_minus_R_slice1"].notna() & df["L2_L_minus_R_slice2"].notna()
    df["slices_agree"] = pd.Series(np.where(have, np.sign(df["L2_L_minus_R_slice1"]) == np.sign(df["L2_L_minus_R_slice2"]), None), dtype=object)
    csvmeta.write_csv(df, out / "inferred_paw.csv", dict(meta_out, table="inferred_paw"))

    n_r, n_l = int((df.inferred_paw == "right").sum()), int((df.inferred_paw == "left").sum())
    test("inferred handedness", n_right_pawed=n_r, n_left_pawed=n_l, binomial_p_vs_50_50=float(stats.binomtest(n_r, n_r + n_l).pvalue))
    test("L2 contra-ipsi (CIRCULAR: used to pick the side)", mean=float(df.L2_contra_minus_ipsi.mean()),
         mean_pct=float(df.L2_asymmetry_pct.mean()), median_pct=float(df.L2_asymmetry_pct.median()), n=len(df))
    agree = int(both.apply(lambda r: np.sign(r.L2_L_minus_R_slice1) == np.sign(r.L2_L_minus_R_slice2), axis=1).sum())
    test("L2 side replicates across the two slices", agree=agree, n=len(both), binomial_p=float(stats.binomtest(agree, len(both)).pvalue))
    l5 = df.dropna(subset=["L5_contra_minus_ipsi"])
    t = stats.ttest_1samp(l5.L5_contra_minus_ipsi, 0); w = stats.wilcoxon(l5.L5_contra_minus_ipsi)
    test("L5 contra-ipsi on the L2-inferred side (independent)", mean=float(l5.L5_contra_minus_ipsi.mean()), n=len(l5),
         contra_gt_ipsi=int((l5.L5_contra_minus_ipsi > 0).sum()), t=float(t.statistic), p_t=float(t.pvalue), p_wilcoxon=float(w.pvalue))
    for paw in ("right", "left"):
        g = l5[l5.inferred_paw == paw]
        if len(g) >= 3:
            w = stats.wilcoxon(g.L5_contra_minus_ipsi)
            test(f"L5 contra-ipsi, inferred {paw}-pawed", mean=float(g.L5_contra_minus_ipsi.mean()), n=len(g),
                 contra_gt_ipsi=int((g.L5_contra_minus_ipsi > 0).sum()), p_wilcoxon=float(w.pvalue))
    r_, l_ = df[df.inferred_paw == "right"].L2_asymmetry_pct, df[df.inferred_paw == "left"].L2_asymmetry_pct
    mw = stats.mannwhitneyu(r_, l_)
    test("L2 asymmetry %: inferred right- vs left-pawed (CIRCULAR side, non-circular magnitude)", right_mean=float(r_.mean()), left_mean=float(l_.mean()),
         p_mannwhitney=float(mw.pvalue))
    ct = pd.crosstab(df.inferred_paw, df.balanced_cluster)
    if ct.shape == (2, 2):
        fe = stats.fisher_exact(ct.to_numpy())
        test("inferred paw vs balanced cluster", crosstab=ct.to_numpy().tolist(), fisher_p=float(fe[1]))
    for layer in ("L2", "L5"):
        col = f"{layer}_contra_minus_ipsi"
        c0, c1 = df[df.balanced_cluster == 0][col].dropna(), df[df.balanced_cluster == 1][col].dropna()
        mw = stats.mannwhitneyu(c0, c1)
        test(f"{layer} contra-ipsi by balanced cluster", cluster0_mean=float(c0.mean()), cluster1_mean=float(c1.mean()), p_mannwhitney=float(mw.pvalue))
    # ── tDCS set-up: balanced clusters as the stim/sham candidates, sides as inferred above ─────────────────────────
    rng = np.random.default_rng(a.seed)
    side = df.set_index("animal")["contra_hemisphere"]
    lvl = somas.groupby(["animal", "layer", "hemisphere"])[m].mean().reset_index()
    lvl = lvl[lvl.animal.isin(side.index)]
    lvl["side"] = np.where(lvl.hemisphere == lvl.animal.map(side), "contra", "ipsi")
    wide = lvl.pivot_table(index=["animal", "layer"], columns="side", values=m).reset_index()
    wide["contra_minus_ipsi"] = wide["contra"] - wide["ipsi"]
    wide = wide.merge(asg[["animal", "kmeans"]], on="animal").rename(columns={"kmeans": "cluster"})
    csvmeta.write_csv(wide, out / "contra_ipsi_by_rat.csv", dict(meta_out, table="contra_ipsi_by_rat"))
    trows = []
    for layer in ("L2", "L5"):
        for q in ("contra", "ipsi", "contra_minus_ipsi"):
            w = wide[wide.layer == layer].dropna(subset=[q])
            g0, g1 = w[w.cluster == 0][q].to_numpy(), w[w.cluster == 1][q].to_numpy()
            obs = g0.mean() - g1.mean()
            boots = np.array([rng.choice(g0, len(g0)).mean() - rng.choice(g1, len(g1)).mean() for _ in range(a.bootstrap)])
            pooled = np.concatenate([g0, g1]); n0 = len(g0)
            perm = np.array([(lambda p: p[:n0].mean() - p[n0:].mean())(rng.permutation(pooled)) for _ in range(a.bootstrap)])
            p_perm = float((np.abs(perm) >= abs(obs)).mean())
            trows.append({"layer": layer, "quantity": q, "cluster0_mean": g0.mean(), "cluster1_mean": g1.mean(), "n0": n0, "n1": len(g1),
                          "difference": obs, "ratio": g0.mean() / g1.mean() if g1.mean() else np.nan,
                          "ci95_low": np.percentile(boots, 2.5), "ci95_high": np.percentile(boots, 97.5), "p_permutation": p_perm})
            print(f"tDCS set-up {layer} {q}: cluster0 {g0.mean():.4g} (n={n0}) vs cluster1 {g1.mean():.4g} (n={len(g1)}); "
                  f"diff {obs:+.4g} [95% CI {np.percentile(boots, 2.5):+.4g}, {np.percentile(boots, 97.5):+.4g}], permutation p = {p_perm:.3f}")
    csvmeta.write_csv(pd.DataFrame(trows), out / "tdcs_by_cluster.csv", dict(meta_out, table="tdcs_by_cluster"))
    csvmeta.write_csv(pd.DataFrame(tests), out / "tests.csv", dict(meta_out, table="inferred_paw_tests"))
    shutil.copy(__file__, out / Path(__file__).name)
    (out / "README.md").write_text(f"# Inferred dominant paw (assumption: contralateral > ipsilateral in Layer 2)\n\nMetric `{m}`, "
                                   f"analysis `{meta.get('analysis_id')}`. Re-run: `python3 {Path(__file__).name} <analysis folder> --metric {m}` "
                                   "from a checkout holding `synapse_analysis/`.\n\n`inferred_paw.csv`: one row per rat; `tests.csv`: the comparisons.\n")
    print(f"\nwrote {out}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
