"""Per-rat gain correction (analysis addendum, 2026-10-14). The raters counted every colocalized terminal on each
labelled neuron's best plane; the pipeline's best-plane count on the same somas is lower by a factor that varies
with staining from rat to rat. `gain_by_animal` measures that factor per rat (human mean / pipeline mean over the
labelled somas) and `apply_gain` multiplies the rat's metrics by it, keeping the raw columns. Rats with fewer
labelled neurons than `min_neurons` keep gain 1 (the gain is still reported, flagged as not applied)."""
from __future__ import annotations

import numpy as np
import pandas as pd

GAIN_COLUMNS = ("animal", "n_neurons", "human_mean", "pipeline_mean", "gain", "applied")


def gain_by_animal(somas: pd.DataFrame, calibration: pd.DataFrame, params) -> pd.DataFrame:
    gc = params.gain_correction
    cols = ["stack", "soma_id", "animal", gc.metric]
    if len(calibration) == 0 or len(somas) == 0 or gc.metric not in somas.columns:
        return pd.DataFrame({c: pd.Series([], dtype=object) for c in GAIN_COLUMNS})
    m = calibration.merge(somas[cols], on=["stack", "soma_id"], how="inner")
    m[gc.metric] = pd.to_numeric(m[gc.metric], errors="coerce")
    m = m.dropna(subset=[gc.metric])
    rows = []
    for animal, g in m.groupby("animal", sort=True):
        hm, pm = float(g["n_clicks"].mean()), float(g[gc.metric].mean())
        gain = hm / pm if pm > 0 else np.nan
        rows.append({"animal": animal, "n_neurons": int(len(g)), "human_mean": hm, "pipeline_mean": pm, "gain": gain,
                     "applied": bool(gc.enabled and len(g) >= gc.min_neurons and np.isfinite(gain))})
    return pd.DataFrame(rows, columns=list(GAIN_COLUMNS))


def apply_gain(somas: pd.DataFrame, gains: pd.DataFrame, metrics) -> pd.DataFrame:
    out = somas.copy()
    factor = gains[gains["applied"]].set_index("animal")["gain"] if len(gains) else pd.Series(dtype=float)
    f = out["animal"].astype(str).map(factor).fillna(1.0).astype(float) if len(out) else pd.Series([], dtype=float)
    out["gain_applied"] = f
    for m in metrics:
        if m in out.columns:
            out[f"{m}_raw"] = out[m]
            out[m] = pd.to_numeric(out[m], errors="coerce") * f
    return out
