"""Which times-table facts are hardest? Reanalysis of the open Moravec dataset.

Source: Zimmerman F, Shalom D, Gonzalez PA, Garrido JM, Alvarez Heduan F, Dehaene S,
Sigman M, Rieznik A (2016). Arithmetic on your phone: a large scale investigation of
simple additions and multiplications. PLoS ONE 11(12): e0168431.
Data: https://doi.org/10.6084/m9.figshare.4288877.v1 (CC BY 4.0), file moravec_data.rar,
MD5 13d58e4ff994eff80ba3b485c272242a. Extract Data_Para_R.csv and pass its path.

Usage: python3 calculate.py Data_Para_R.csv OUTPUT_DIR
Requires: Python 3.10+, numpy, pandas. statsmodels is optional (validation step only).
Writes facts.csv, ordered_facts.csv, by_table.csv, sensitivity.csv and summary.json.
"""

import json
import sys
from pathlib import Path

import numpy as np
import pandas as pd

SEED = 20261125
N_BOOT = 1000


def load(path):
    d = pd.read_csv(path)
    m = d[d.Operation_Type == "1dx1d"].copy()
    m["a"] = m[["Operand_1", "Operand_2"]].min(axis=1)
    m["b"] = m[["Operand_1", "Operand_2"]].max(axis=1)
    m["fact"] = m.a.astype(str) + "x" + m.b.astype(str)
    m["product"] = m.Operand_1 * m.Operand_2
    m["tie"] = m.Operand_1 == m.Operand_2
    return m


def rt_set(m):
    r = m[(m.Correct == 1) & (m.Erase == 0) & (m.Total_Time > 0)]
    cut = r.Total_Time.mean() + 4 * r.Total_Time.std()
    return r[r.Total_Time < cut].copy(), cut


def err_set(m):
    return m[(m.Erase == 0) & (m.Total_Time > 0)].copy()


def fact_effects(r, facts, iters=200):
    """log RT = user + fact; returns fact effects centred on the unweighted fact mean."""
    y = np.log(r.Total_Time.to_numpy(float))
    u_idx = pd.factorize(r.AUID)[0]
    f_idx = pd.Categorical(r.fact, categories=facts).codes
    nu, nf = u_idx.max() + 1, len(facts)
    cu = np.bincount(u_idx, minlength=nu)
    cf = np.bincount(f_idx, minlength=nf)
    u = np.zeros(nu)
    f = np.zeros(nf)
    for _ in range(iters):
        u = np.bincount(u_idx, y - f[f_idx], nu) / cu
        f_new = np.bincount(f_idx, y - u[u_idx], nf) / np.maximum(cf, 1)
        if np.max(np.abs(f_new - f)) < 1e-10:
            f = f_new
            break
        f = f_new
    f = f - f[cf > 0].mean()
    f[cf == 0] = np.nan
    return f


def per_fact(r, e, facts):
    eff = fact_effects(r, facts)
    g = r.groupby("fact").Total_Time
    ge = e.groupby("fact")
    out = pd.DataFrame(index=facts)
    out["rt_trials"] = g.size().reindex(facts)
    out["users"] = r.groupby("fact").AUID.nunique().reindex(facts)
    out["median_rt_ms"] = g.median().reindex(facts)
    out["rel_time_pct"] = 100 * (np.exp(eff) - 1)
    out["attempts"] = ge.size().reindex(facts)
    out["error_pct"] = 100 * (1 - ge.Correct.mean().reindex(facts))
    return out


def bootstrap(r, e, facts):
    rng = np.random.default_rng(SEED)
    users = np.array(sorted(r.AUID.unique().tolist() + list(set(e.AUID) - set(r.AUID))))
    r_by = {k: v for k, v in r.groupby("AUID")}
    e_by = {k: v for k, v in e.groupby("AUID")}
    rel, err, rank = [], [], []
    for _ in range(N_BOOT):
        pick = rng.choice(users, size=len(users), replace=True)
        rr, ee = [], []
        for i, uid in enumerate(pick):
            if uid in r_by:
                x = r_by[uid].copy()
                x["AUID"] = f"{uid}#{i}"
                rr.append(x)
            if uid in e_by:
                ee.append(e_by[uid])
        rb, eb = pd.concat(rr), pd.concat(ee)
        f = fact_effects(rb, facts, iters=100)
        rel.append(100 * (np.exp(f) - 1))
        rank.append(pd.Series(-f).rank(method="min").to_numpy())
        err.append(100 * (1 - eb.groupby("fact").Correct.mean().reindex(facts).to_numpy()))
    rel, err, rank = map(np.array, (rel, err, rank))
    q = lambda a, p: np.nanpercentile(a, p, axis=0)
    return {
        "rel_lo": q(rel, 2.5), "rel_hi": q(rel, 97.5),
        "err_lo": q(err, 2.5), "err_hi": q(err, 97.5),
        "rank_lo": q(rank, 2.5), "rank_hi": q(rank, 97.5),
        "top5_share": (rank <= 5).mean(axis=0),
    }


def spearman(x, y):
    return float(pd.Series(x).rank().corr(pd.Series(y).rank()))


def validate(m):
    """Reproduce the published multiplication size-effect fits (authors' filters)."""
    try:
        import statsmodels.formula.api as smf
    except ImportError:
        return {"skipped": "statsmodels not installed"}
    res = {}
    for name, tie in (("non_ties", False), ("ties", True)):
        x = m[(m.Correct == 1) & (m.Erase == 0) & (m.Total_Time > 0) & (m.tie == tie)]
        x = x[x.Total_Time < x.Total_Time.mean() + 4 * x.Total_Time.std()]
        fit = smf.mixedlm("Total_Time ~ product", x, groups=x["AUID"]).fit(reml=True)
        res[name] = {"trials": int(len(x)), "intercept_ms": round(float(fit.params["Intercept"]), 1),
                     "slope_ms_per_unit": round(float(fit.params["product"]), 2)}
    return res


def main(csv_path, out_dir):
    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    m = load(csv_path)
    facts = sorted(m.fact.unique(), key=lambda s: (int(s.split("x")[0]), int(s.split("x")[1])))
    r, cut = rt_set(m)
    e = err_set(m)

    summary = {
        "multiplication_trials": int(len(m)),
        "users": int(m.AUID.nunique()),
        "rt_trials": int(len(r)),
        "rt_users": int(r.AUID.nunique()),
        "rt_cut_ms": round(float(cut), 1),
        "error_trials": int(len(e)),
        "overall_error_pct": round(100 * (1 - e.Correct.mean()), 2),
        "overall_median_rt_ms": float(r.Total_Time.median()),
        "validation": validate(m),
    }

    t = per_fact(r, e, facts)
    b = bootstrap(r, e, facts)
    for k, v in b.items():
        t[k] = v
    t["product"] = [int(s.split("x")[0]) * int(s.split("x")[1]) for s in facts]
    t["tie"] = [s.split("x")[0] == s.split("x")[1] for s in facts]
    t["speed_rank"] = t.rel_time_pct.rank(ascending=False, method="min").astype(int)
    t["error_rank"] = t.error_pct.rank(ascending=False, method="min").astype(int)
    t.index.name = "fact"
    t = t.round(2)
    t.to_csv(out / "facts.csv")

    summary["spearman_speed_vs_error"] = round(spearman(t.rel_time_pct, t.error_pct), 3)
    summary["spearman_speed_vs_product"] = round(spearman(t.rel_time_pct, t["product"]), 3)
    nt = t[~t.tie]
    summary["spearman_speed_vs_product_non_ties"] = round(spearman(nt.rel_time_pct, nt["product"]), 3)
    summary["slowest5"] = t.sort_values("rel_time_pct", ascending=False).head(5).index.tolist()
    summary["fastest5"] = t.sort_values("rel_time_pct").head(5).index.tolist()
    summary["most_errors5"] = t.sort_values("error_pct", ascending=False).head(5).index.tolist()

    # Per table (every fact containing n, ties counted once), speed-adjusted mean of fact effects
    rows = []
    for n in range(2, 10):
        sel = [f for f in facts if str(n) in f.split("x")]
        rows.append({"table": n, "facts": len(sel),
                     "mean_rel_time_pct": round(float(t.loc[sel, "rel_time_pct"].mean()), 2),
                     "mean_error_pct": round(float(t.loc[sel, "error_pct"].mean()), 2)})
    pd.DataFrame(rows).to_csv(out / "by_table.csv", index=False)

    # Ordered facts: a x b with the larger operand first vs second
    ro = r.copy()
    ro["larger_first"] = ro.Operand_1 > ro.Operand_2
    nt_r = ro[~ro.tie]
    eff_ord = []
    for f, g in nt_r.groupby("fact"):
        med = g.groupby("larger_first").Total_Time.median()
        eff_ord.append({"fact": f, "trials_larger_first": int((g.larger_first).sum()),
                        "trials_smaller_first": int((~g.larger_first).sum()),
                        "median_rt_larger_first": float(med.get(True, np.nan)),
                        "median_rt_smaller_first": float(med.get(False, np.nan))})
    pd.DataFrame(eff_ord).to_csv(out / "ordered_facts.csv", index=False)

    # Wrong typed answers (time-outs excluded): which numbers people entered instead
    products = {i * j for i in range(2, 10) for j in range(2, 10)}
    w = e[(e.Correct == 0) & (e.Time_Exceeded == 0)].copy()
    w["answer"] = w.Entered_Answer.astype(int)
    w["table_neighbour"] = [
        x in {a * (b + 1), a * (b - 1), (a + 1) * b, (a - 1) * b}
        for a, b, x in zip(w.Operand_1, w.Operand_2, w.answer)
    ]
    w["other_fact_product"] = w.answer.isin(products) & (w.answer != w.Correct_Result)
    summary["timeouts"] = int(((e.Correct == 0) & (e.Time_Exceeded == 1)).sum())
    summary["wrong_typed_answers"] = int(len(w))
    summary["wrong_table_neighbour_pct"] = round(100 * float(w.table_neighbour.mean()), 1)
    summary["wrong_other_fact_product_pct"] = round(100 * float(w.other_fact_product.mean()), 1)
    wrows = []
    for f in facts:
        x = w[w.fact == f]
        vc = x.answer.value_counts().head(3)
        wrows.append({"fact": f, "wrong_typed": int(len(x)),
                      "top_wrong_answers": " ".join(f"{k}({v})" for k, v in vc.items()),
                      "table_neighbour_pct": round(100 * float(x.table_neighbour.mean()), 1) if len(x) else None,
                      "other_fact_product_pct": round(100 * float(x.other_fact_product.mean()), 1) if len(x) else None})
    pd.DataFrame(wrows).to_csv(out / "wrong_answers.csv", index=False)

    # Sensitivity analyses: rank agreement with the primary speed index
    sens = []
    trials_per_user = m.groupby("AUID").size()
    variants = {
        "arcade_only": m[m.Game_Type == "Arcade"],
        "question_visible_only": m[m.Hide_Question == 0],
        "users_20plus_trials": m[m.AUID.isin(trials_per_user[trials_per_user >= 20].index)],
    }
    for name, mv in variants.items():
        rv, _ = rt_set(mv)
        ev = err_set(mv)
        tv = per_fact(rv, ev, facts)
        top = tv.sort_values("rel_time_pct", ascending=False).head(5).index.tolist()
        sens.append({"variant": name, "rt_trials": int(len(rv)), "users": int(rv.AUID.nunique()),
                     "spearman_with_primary": round(spearman(tv.rel_time_pct, t.rel_time_pct), 3),
                     "slowest5": " ".join(top),
                     "overlap_with_primary_slowest5": len(set(top) & set(summary["slowest5"]))})
    pd.DataFrame(sens).to_csv(out / "sensitivity.csv", index=False)

    (out / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit(__doc__)
    main(sys.argv[1], sys.argv[2])
