"""Giving History Analysis: the Python half of the aysra browser tool.

Runs inside Pyodide in a Web Worker. Nothing here touches the network or
disk outside Pyodide's in-memory filesystem. The worker calls analyze() with
gift rows the page has already stripped of contact columns, and gets back
one JSON-safe dict.

Built on PhilanthroPy 0.10.0 by Shivam Lalakiya (MIT license). Whether a
list uses the model or a simple rule is decided by the library's own
compare_to_rule: the model must beat the best rule across a 95% bootstrap
interval on the file's most recent complete year, and every tie goes to
the rule.
"""

from __future__ import annotations

from typing import Any, Dict, List, Optional

import numpy as np
import pandas as pd

import philanthropy
from philanthropy.ingest import build_snapshots, read_gift_rows
from philanthropy.model_selection import compare_to_rule, rule_scores
from philanthropy.models import DonorPropensityModel, LapsePredictor, MajorGiftClassifier

DONOR_CAP = 2000
N_BOOTSTRAP = 200          # Shivam's guidance for Pyodide: about 24 s on a 90,000-row test year
TOP_FRACTION = 0.10        # the library's check compares the top 10%
NEXT_FRACTION = 0.30       # the next 30%, shown as a second group
APPEAL_FRACTION = 0.50     # year-end appeal list: the top half of the same order
RANDOM_STATE = 0

# Mirrors philanthropy.model_selection._rule_check so the page's own
# group rates and gains curve come from the same rows the check scored.
_KIND = {"response": "response_next_year", "lapse": "lapse", "upgrade": "upgrade"}
_MIN_YEARS = {"response": 1, "lapse": 2, "upgrade": 1}

CRM_SOURCES = {"raisers_edge", "npsp", "nonprofit_cloud", "bloomerang", "donorperfect",
               "civicrm", "blackbaud_crm", "little_green_light", "ellucian_advance"}


# --------------------------------------------------------------------------- #
# Reading the file
# --------------------------------------------------------------------------- #
def to_gift_rows(rows: List[Dict[str, Any]], source: str, mapping: Optional[Dict[str, str]]) -> pd.DataFrame:
    raw = pd.DataFrame(rows, dtype="object")
    mapping = {k: v for k, v in (mapping or {}).items() if v and v in raw.columns}
    if source in CRM_SOURCES:
        if mapping:
            # The user's confirmed columns win over the reader's own header guesses.
            canon = {"donor_id": "contact_id", "gift_date": "receive_date", "gift_amount": "total_amount"}
            taken = {canon[k] for k in mapping}
            raw = raw.drop(columns=[c for c in raw.columns if c in taken and c not in mapping.values()])
            raw = raw.rename(columns={v: canon[k] for k, v in mapping.items()})
        try:
            df = read_gift_rows(raw, source=source)
        except KeyError as err:
            raise ValueError("missing:donor_id,gift_date,gift_amount") from err
    else:
        df = raw.rename(columns={v: k for k, v in mapping.items()})
        missing = [c for c in ("donor_id", "gift_date", "gift_amount") if c not in df.columns]
        if missing:
            raise ValueError("missing:" + ",".join(missing))
        df = pd.DataFrame({
            "donor_id": df["donor_id"].astype("string").str.strip(),
            "gift_date": pd.to_datetime(df["gift_date"], errors="coerce"),
            "gift_amount": pd.to_numeric(
                df["gift_amount"].astype("string").str.replace(r"[$,\s]", "", regex=True), errors="coerce"
            ),
        })
    df = df[df["donor_id"].notna() & (df["donor_id"].astype("string").str.strip() != "")
            & df["gift_date"].notna() & df["gift_amount"].notna()]
    return df[["donor_id", "gift_date", "gift_amount"]].reset_index(drop=True)


# --------------------------------------------------------------------------- #
# Fiscal years, in the library's own labelling
# --------------------------------------------------------------------------- #
# Written out here rather than imported from the library's private modules, so a
# later release can move them without breaking this page. Same convention as
# PhilanthroPy 0.10.0: a fiscal year is named for the calendar year it ends in,
# and a January start makes the fiscal year the calendar year.
def fiscal_year(dates: pd.Series, start_month: int) -> pd.Series:
    year = dates.dt.year
    if start_month == 1:
        return year.astype("int64")
    return (year + (dates.dt.month >= start_month).astype("int64")).astype("int64")


def fy_end(fy: int, start_month: int) -> pd.Timestamp:
    end_year = int(fy) + 1 if start_month == 1 else int(fy)
    return pd.Timestamp(year=end_year, month=start_month, day=1) - pd.Timedelta(days=1)


def fy_start(fy: int, start_month: int) -> pd.Timestamp:
    return fy_end(fy - 1, start_month) + pd.Timedelta(days=1)


def _date(ts: pd.Timestamp) -> str:
    return pd.Timestamp(ts).strftime("%Y-%m-%d")


# --------------------------------------------------------------------------- #
# Descriptive sections
# --------------------------------------------------------------------------- #
def retention_table(gifts, last_complete, first_fy, in_progress, start_month):
    gave = gifts[gifts["gift_amount"] > 0].groupby("fy")["donor_id"].apply(set)
    rows = []
    for fy in range(max(first_fy + 1, last_complete - 4), last_complete + 1):
        prior = gave.get(fy - 1, set())
        if not prior:
            continue
        kept = len(prior & gave.get(fy, set()))
        rows.append({"fiscal_year": fy, "from": _date(fy_start(fy, start_month)), "to": _date(fy_end(fy, start_month)),
                     "prior_donors": len(prior), "gave_again": kept, "kept": kept / len(prior)})
    if in_progress is not None:
        rows.append({"fiscal_year": in_progress, "from": _date(fy_start(in_progress, start_month)),
                     "to": _date(fy_end(in_progress, start_month)),
                     "prior_donors": len(gave.get(in_progress - 1, set())), "gave_again": None, "kept": None})
    return rows


def standing_table(gifts: pd.DataFrame, as_of: pd.Timestamp) -> Dict[str, Any]:
    pos = gifts[gifts["gift_amount"] > 0]
    by = pos.groupby("donor_id").agg(last=("gift_date", "max"), years=("fy", "nunique"), total=("gift_amount", "sum"))
    months = (as_of - by["last"]).dt.days / 30.44
    groups = [
        ("Gave in the last 12 months, in 5 or more fiscal years", (months <= 12) & (by["years"] >= 5)),
        ("Gave in the last 12 months, in 2 to 4 fiscal years", (months <= 12) & by["years"].between(2, 4)),
        ("Gave in the last 12 months, in 1 fiscal year", (months <= 12) & (by["years"] == 1)),
        ("Last gift 1 to 2 years ago, gave in 3 or more fiscal years", (months > 12) & (months <= 24) & (by["years"] >= 3)),
        ("Last gift 1 to 2 years ago, gave in 1 or 2 fiscal years", (months > 12) & (months <= 24) & (by["years"] <= 2)),
        ("No gift in over 2 years", months > 24),
    ]
    total = float(by["total"].sum()) or 1.0
    rows = [{"group": label, "donors": int(mask.sum()), "share": float(by.loc[mask, "total"].sum()) / total}
            for label, mask in groups]
    # Concentration: share of all giving from the top 1%, 5% and 10% of donors by lifetime total.
    ranked = by["total"].sort_values(ascending=False).to_numpy()
    n = len(ranked)
    concentration = [{"top_fraction": f, "donors": max(1, int(round(n * f))),
                      "share": float(ranked[:max(1, int(round(n * f)))].sum()) / total} for f in (0.01, 0.05, 0.10)]
    return {"as_of": _date(as_of), "rows": rows, "concentration": concentration, "n_donors": n}


# --------------------------------------------------------------------------- #
# One task: the library's verdict, plus the same check's rows for the page
# --------------------------------------------------------------------------- #
def _features(snap: pd.DataFrame) -> List[str]:
    return [c for c in snap.columns if c not in ("period", "target") and pd.api.types.is_numeric_dtype(snap[c])]


def _model(task: str):
    if task == "response":
        return DonorPropensityModel(random_state=RANDOM_STATE)
    if task == "lapse":
        return LapsePredictor(random_state=RANDOM_STATE)
    return MajorGiftClassifier(random_state=RANDOM_STATE)


def _score(task: str, model, X: np.ndarray) -> np.ndarray:
    if task == "lapse":
        return np.asarray(model.predict_lapse_score(X), dtype="float64")
    return np.asarray(model.predict_proba(X)[:, 1], dtype="float64")


def run_task(task: str, gifts: pd.DataFrame, as_of: pd.Timestamp, last_complete: int, first_fy: int,
             start_month: int) -> Dict[str, Any]:
    rows = gifts[["donor_id", "gift_date", "gift_amount"]]
    check = compare_to_rule(rows, task=task, as_of=as_of, fiscal_year_start=start_month,
                            n_bootstrap=N_BOOTSTRAP, random_state=RANDOM_STATE)
    out: Dict[str, Any] = {"task": task, "method": check["method"], "verdict": check["verdict"],
                           "rule": check["rule"], "test_fy": check["test_fiscal_year"],
                           "n_test": check["n_test"], "model_rate": check["model_value"],
                           "rule_rate": check["rule_value"], "ci": check["difference_ci"],
                           "label_floor": check["label_floor"]}
    kind, min_years = _KIND[task], _MIN_YEARS[task]
    snaps = build_snapshots(rows, kind=kind, fiscal_years=range(first_fy, last_complete),
                            min_years_given=min_years, fiscal_year_start=start_month, cadence=task == "lapse")
    if snaps.empty or check["test_fiscal_year"] is None:
        out["available"] = False
        out["positives"] = int(snaps["target"].sum()) if not snaps.empty else 0
        return out
    test_fy = int(check["test_fiscal_year"])
    train, test = snaps[snaps["period"] < test_fy], snaps[snaps["period"] == test_fy]
    out["positives"] = int(train["target"].sum())
    out["available"] = check["verdict"] not in ("not enough labels",) and not check["verdict"].startswith("can't test")
    if not out["available"]:
        return out

    cols = _features(snaps)
    y = test["target"].to_numpy("float64")
    rule_test = rule_scores(test, task=task, gifts=rows if task == "response" else None,
                            rule=check["rule"], fiscal_year_start=start_month).to_numpy("float64")
    model = _model(task).fit(train[cols].fillna(0.0).to_numpy("float64"), train["target"].to_numpy("float64"))
    model_test = _score(task, model, test[cols].fillna(0.0).to_numpy("float64"))
    n = len(y)
    k = max(1, int(round(n * TOP_FRACTION)))

    def order(score):
        return np.argsort(-score, kind="stable")

    # The page's counts come from the same rows the check scored. If they ever
    # disagree with the check's rates, the page shows the check's rates only.
    mine_rule, mine_model = float(y[order(rule_test)[:k]].mean()), float(y[order(model_test)[:k]].mean())
    out["consistent"] = (abs(mine_rule - (check["rule_value"] or 0)) < 1e-9
                         and abs(mine_model - (check["model_value"] or 0)) < 1e-9)
    chosen = model_test if check["method"] == "model" else rule_test
    ch = order(chosen)
    k_next = max(k + 1, int(round(n * (TOP_FRACTION + NEXT_FRACTION))))
    out.update({
        "k": k, "base_rate": float(y.mean()), "test_positives": int(y.sum()),
        "model_hits": int(y[order(model_test)[:k]].sum()), "rule_hits": int(y[order(rule_test)[:k]].sum()),
        "built_through": _date(fy_end(test_fy, start_month)),
        "checked_from": _date(fy_start(test_fy + 1, start_month)),
        "checked_to": _date(fy_end(test_fy + 1, start_month)),
        "groups": [float(y[ch[:k]].mean()), float(y[ch[k:k_next]].mean()) if k_next > k else None,
                   float(y[ch[k_next:]].mean()) if n > k_next else None],
        # Gains curve: share of the test year's positives found by the first 10%, 20% ... 100% of each list.
        "gains": [{"fraction": f / 10,
                   "model": float(y[order(model_test)[:max(1, round(n * f / 10))]].sum()) / max(1.0, y.sum()),
                   "rule": float(y[order(rule_test)[:max(1, round(n * f / 10))]].sum()) / max(1.0, y.sum())}
                  for f in range(1, 11)],
    })
    if task == "response":
        tiers = [("Under $100", test["period_total"] < 100),
                 ("$100 to $999", (test["period_total"] >= 100) & (test["period_total"] < 1000)),
                 ("$1,000 or more", test["period_total"] >= 1000)]
        out["by_tier"] = [{"tier": label, "donors": int(mask.sum()),
                           "rate": float(test.loc[mask, "target"].mean()) if mask.any() else None}
                          for label, mask in tiers]

    # Score the donors as of the latest complete year, with whichever side won.
    now = build_snapshots(rows, kind=kind, score_period=last_complete, min_years_given=min_years,
                          fiscal_year_start=start_month, cadence=task == "lapse")
    if now.empty:
        out["available"] = False
        return out
    if check["method"] == "model":
        full = _model(task).fit(snaps[cols].fillna(0.0).to_numpy("float64"), snaps["target"].to_numpy("float64"))
        now_score = pd.Series(_score(task, full, now[cols].fillna(0.0).to_numpy("float64")), index=now.index)
    else:
        now_score = rule_scores(now, task=task, gifts=rows if task == "response" else None,
                                rule=check["rule"], fiscal_year_start=start_month).astype("float64")
    out["_now"] = now_score.sort_values(ascending=False, kind="mergesort")
    out["scored_as_of"] = _date(fy_end(last_complete, start_month))
    return out


# --------------------------------------------------------------------------- #
# Entry point
# --------------------------------------------------------------------------- #
def _clean(obj):
    if isinstance(obj, dict):
        return {k: _clean(v) for k, v in obj.items() if not str(k).startswith("_")}
    if isinstance(obj, (list, tuple)):
        return [_clean(v) for v in obj]
    if isinstance(obj, (np.floating, float)):
        return None if np.isnan(obj) else float(obj)
    if isinstance(obj, np.integer):
        return int(obj)
    return obj


def analyze(rows: List[Dict[str, Any]], source: str, mapping: Optional[Dict[str, str]],
            fiscal_year_start: int, export_date: str) -> Dict[str, Any]:
    gifts = to_gift_rows(rows, source, mapping)
    as_of = pd.Timestamp(export_date)
    gifts = gifts[gifts["gift_date"] <= as_of].reset_index(drop=True)
    if gifts.empty:
        return {"ok": False, "error": "no_gifts"}
    n_donors = int(gifts["donor_id"].nunique())
    base = {"n_gifts": int(len(gifts)), "n_donors": n_donors, "as_of": _date(as_of),
            "first_gift": _date(gifts["gift_date"].min()), "last_gift": _date(gifts["gift_date"].max()),
            "library_version": philanthropy.__version__}
    if n_donors > DONOR_CAP:
        return {"ok": False, "error": "over_cap", **base}

    gifts["fy"] = fiscal_year(gifts["gift_date"], fiscal_year_start)
    fy_as_of = int(fiscal_year(pd.Series([as_of]), fiscal_year_start).iloc[0])
    year_done = as_of >= fy_end(fy_as_of, fiscal_year_start)
    in_progress = None if year_done else fy_as_of
    last_complete = fy_as_of if year_done else fy_as_of - 1
    first_fy = int(gifts["fy"].min())

    result: Dict[str, Any] = {"ok": True, **base, "fiscal_year_start": fiscal_year_start,
                              "last_complete_fy": last_complete, "in_progress_fy": in_progress, "first_fy": first_fy}
    result["retention"] = retention_table(gifts, last_complete, first_fy, in_progress, fiscal_year_start)
    result["standing"] = standing_table(gifts, as_of)

    tasks = {}
    for task in ("response", "lapse", "upgrade"):
        try:
            tasks[task] = run_task(task, gifts, as_of, last_complete, first_fy, fiscal_year_start)
        except Exception as err:  # one task failing never blocks the others
            tasks[task] = {"task": task, "available": False, "verdict": "can't test (" + type(err).__name__ + ")"}

    # One row per donor for the downloads.
    pos = gifts[gifts["gift_amount"] > 0].sort_values("gift_date")
    per = pos.groupby("donor_id").agg(last_gift_date=("gift_date", "max"), years_given=("fy", "nunique"),
                                      total_given=("gift_amount", "sum"), first_gift_date=("gift_date", "min"))
    per["last_gift_amount"] = pos.groupby("donor_id")["gift_amount"].last()
    # Largest gift in the last three complete fiscal years and the year in progress.
    recent = pos[pos["fy"].between(last_complete - 2, in_progress if in_progress is not None else last_complete)]
    per["suggested_ask"] = recent.groupby("donor_id")["gift_amount"].max()
    this_year = pos[pos["fy"] == in_progress].groupby("donor_id")["gift_amount"].sum() if in_progress else pd.Series(dtype=float)

    resp = tasks["response"].get("_now")
    lapse = tasks["lapse"].get("_now")
    upg = tasks["upgrade"].get("_now")
    resp_rank = pd.Series(np.arange(1, len(resp) + 1), index=resp.index) if resp is not None else None
    m = len(resp) if resp is not None else 0
    n_top, n_next, n_mail = (max(1, round(m * TOP_FRACTION)), max(1, round(m * (TOP_FRACTION + NEXT_FRACTION))),
                             max(1, round(m * APPEAL_FRACTION)))
    # Lapse list: the top 10% at risk among donors who have not given yet this fiscal year.
    lapse_ids = set()
    if lapse is not None:
        eligible = [d for d in lapse.index if d not in this_year.index]
        lapse_ids = set(eligible[:max(1, round(len(lapse) * TOP_FRACTION))])
        tasks["lapse"]["list_size"] = len(lapse_ids)
    upg_rank = pd.Series(np.arange(1, len(upg) + 1), index=upg.index) if upg is not None else None

    donors = []
    for donor_id, r in per.iterrows():
        row = {"donor_id": str(donor_id), "last_gift_date": _date(r["last_gift_date"]),
               "last_gift_amount": round(float(r["last_gift_amount"]), 2), "fiscal_years_given": int(r["years_given"]),
               "total_given": round(float(r["total_given"]), 2), "first_gift_date": _date(r["first_gift_date"])}
        ask = r.get("suggested_ask")
        row["suggested_ask"] = "No recent gift" if ask is None or pd.isna(ask) else round(float(ask), 2)
        if in_progress is not None:
            row["given_this_fiscal_year"] = round(float(this_year.get(donor_id, 0.0)), 2)
        if resp_rank is not None and donor_id in resp_rank.index:
            rk = int(resp_rank[donor_id])
            row["order"] = rk
            row["group"] = "Call or thank first" if rk <= n_top else "Next" if rk <= n_next else "Everyone else"
            row["appeal_list"] = rk <= n_mail
        elif resp_rank is not None:
            row["group"] = "First gift this fiscal year"
            row["appeal_list"] = True
        row["lapse_list"] = donor_id in lapse_ids
        if upg_rank is not None and donor_id in upg_rank.index:
            row["upgrade_rank"] = int(upg_rank[donor_id])
        donors.append(row)
    if resp is not None:
        tasks["response"]["list_sizes"] = {"top": n_top, "next": n_next - n_top, "mail": n_mail, "scored": m}
    result["tasks"] = tasks
    result["donors"] = donors
    return _clean(result)
