"""Objective inclusion rules (analysis spec 3.3): stacks by quality, somas by the rules in params.soma_filter.
A soma gets the FIRST failing rule in RULES order as its reason; a NaN in a filtered column fails that rule."""
from __future__ import annotations

import re

import numpy as np
import pandas as pd

RULES = ("volume_min", "volume_max", "border_fraction", "touches_border", "neun_mean", "no_tail")
QC_COLUMNS = ("stack", "n_total", "n_kept", "n_dropped") + tuple(f"dropped_{r}" for r in RULES)


def filter_stacks(stacks: pd.DataFrame, params):
    """Quality not in the allowed list, or (second) sheet notes matching exclude_note_regex, case-insensitive, or (third)
    the stack's rat named in exclude_animals (case-insensitive)."""
    sf = params.stack_filter
    q = stacks["quality"].astype(str)
    reason = pd.Series([""] * len(stacks), index=stacks.index, dtype=object)
    reason[~q.isin(set(sf.quality))] = "quality=" + q[~q.isin(set(sf.quality))]
    if sf.exclude_animals and "animal" in stacks.columns:
        animals = stacks["animal"].fillna("").astype(str)
        hit = (reason == "") & animals.str.lower().isin({a.lower() for a in sf.exclude_animals})
        reason[hit] = "animal excluded: " + animals[hit]
    if sf.exclude_note_regex and "notes" in stacks.columns:
        pat = re.compile(sf.exclude_note_regex, re.IGNORECASE)
        notes = stacks["notes"].fillna("").astype(str)
        hit = (reason == "") & notes.map(lambda t: bool(pat.search(t)))
        reason[hit] = "note matches /" + sf.exclude_note_regex + "/: " + notes[hit]
    ok = reason == ""
    dropped = pd.DataFrame({"stack": stacks.loc[~ok, "stack"].astype(str).tolist(), "reason": reason[~ok].tolist()}, columns=["stack", "reason"])
    return stacks[ok].reset_index(drop=True), dropped


def _fail_masks(somas: pd.DataFrame, sf) -> dict:
    v = pd.to_numeric(somas["volume_um3"], errors="coerce")
    bf = pd.to_numeric(somas["border_fraction"], errors="coerce")
    nm = pd.to_numeric(somas["neun_mean"], errors="coerce")
    tb = somas["touches_border"]
    touches = tb.isna() | (tb.astype(object) == True)     # noqa: E712  (object compare: NaN/None never equal True)
    if sf.require_tail:
        ht = somas["has_tail"] if "has_tail" in somas.columns else pd.Series(np.nan, index=somas.index, dtype=object)
        no_tail = ~(ht.astype(object) == True)      # noqa: E712  (NaN / missing column = no tail)
    else:
        no_tail = pd.Series(False, index=somas.index)
    return {"volume_min": ~(v >= sf.volume_min_um3), "volume_max": ~(v <= sf.volume_max_um3),
            "border_fraction": ~(bf <= sf.border_fraction_max),
            "touches_border": touches if sf.exclude_touches_border else pd.Series(False, index=somas.index),
            "neun_mean": ~(nm >= sf.neun_mean_min), "no_tail": no_tail}


def filter_somas(somas: pd.DataFrame, params):
    reason = pd.Series([""] * len(somas), index=somas.index, dtype=object)
    if len(somas):
        for rule, fail in _fail_masks(somas, params.soma_filter).items():
            hit = (reason == "") & fail.to_numpy(dtype=bool)
            reason[hit] = rule
    kept = somas[reason == ""].reset_index(drop=True)
    dropped = somas[reason != ""].assign(reason=reason[reason != ""].to_numpy()).reset_index(drop=True)
    if "reason" not in dropped.columns:
        dropped["reason"] = pd.Series([], dtype=object)
    return kept, dropped


def qc_by_stack(somas: pd.DataFrame, kept: pd.DataFrame, dropped: pd.DataFrame, all_stacks=None) -> pd.DataFrame:
    stacks = sorted(set(map(str, all_stacks or [])) | set(somas["stack"].astype(str)))
    if not stacks:
        return pd.DataFrame({c: pd.Series([], dtype=(object if c == "stack" else np.int64)) for c in QC_COLUMNS})
    rows = []
    for s in stacks:
        d = dropped[dropped["stack"].astype(str) == s] if len(dropped) else dropped
        row = {"stack": s, "n_total": int((somas["stack"].astype(str) == s).sum()) if len(somas) else 0,
               "n_kept": int((kept["stack"].astype(str) == s).sum()) if len(kept) else 0, "n_dropped": int(len(d))}
        for r in RULES:
            row[f"dropped_{r}"] = int((d["reason"] == r).sum()) if len(d) else 0
        rows.append(row)
    return pd.DataFrame(rows, columns=list(QC_COLUMNS)).astype({c: np.int64 for c in QC_COLUMNS[1:]})
