"""Compute the Plumb Research Index exactly as specified in METHOD.md (frozen 2026-10-09).

Input : data/raw/leiden2025-Results.xlsx (CWTS Leiden Ranking Open Edition 2025, CC0)
Output: data/processed/scores.json

Usage: python3 pipeline/score.py
"""
import json, re, sys, time, unicodedata
from pathlib import Path

import numpy as np
import pandas as pd

ROOT = Path(__file__).resolve().parent.parent
RAW = ROOT / "data" / "raw" / "leiden2025-Results.xlsx"
CACHE = ROOT / "data" / "raw" / "leiden2025-results.pkl"
OUT = ROOT / "data" / "processed" / ("scores-v1.0.json" if "--v10" in sys.argv else "scores.json")

PERIOD = "2020\u20132023"
FIELD_MIN_P = 200          # METHOD.md: field tables need >= 200 fractional core pubs
OVERALL_MIN_P = 0 if "--v10" in sys.argv else 1500   # METHOD.md Amendment 1 (v1.1); --v10 regenerates the original rule
N_DRAWS = 2000
SEED = 20261009
DIRICHLET = np.array([8.0, 4.0, 6.0])   # centred on 20:10:15
W_POINT = np.array([20.0, 10.0, 15.0])

FIELDS = [
    ("all", "All sciences"),
    ("bio", "Biomedical and health sciences"),
    ("life", "Life and earth sciences"),
    ("math", "Mathematics and computer science"),
    ("phys", "Physical sciences and engineering"),
    ("soc", "Social sciences and humanities"),
]
FIELD_LABEL = {
    "all": "All sciences", "bio": "Biomedical & health sciences", "life": "Life & earth sciences",
    "math": "Mathematics & computer science", "phys": "Physical sciences & engineering", "soc": "Social sciences & humanities",
}


KEEP = ["University", "ROR_ID", "Country", "Field", "Period", "Core_pubs_only", "Frac_counting", "P", "P_top_1", "P_top_10",
        "PP_top_1", "PP_top_1_lb", "PP_top_1_ub", "PP_top_10", "PP_top_10_lb", "PP_top_10_ub", "PP_int_collab", "PP_OA"]


def load():
    """Stream the 1M-row Results sheet once and cache only the rows/columns the method needs."""
    if CACHE.exists() and CACHE.stat().st_mtime > RAW.stat().st_mtime:
        return pd.read_pickle(CACHE)
    from python_calamine import CalamineWorkbook
    t = time.time()
    it = CalamineWorkbook.from_path(str(RAW)).get_sheet_by_name("Results").iter_rows()
    hdr = list(next(it))
    ix = [hdr.index(c) for c in KEEP]
    i_core, i_frac, i_per, i_field = hdr.index("Core_pubs_only"), hdr.index("Frac_counting"), hdr.index("Period"), hdr.index("Field")
    keep = []
    for row in it:
        core, frac = row[i_core] == 1, row[i_frac] == 1
        if (core and frac) or ((not frac) and row[i_per] == PERIOD and row[i_field] == "All sciences"):
            keep.append([row[i] for i in ix])
    df = pd.DataFrame(keep, columns=KEEP)
    print(f"kept {len(df):,} rows in {time.time()-t:.0f}s", file=sys.stderr)
    df.to_pickle(CACHE)
    return df


def col(df, *cands):
    norm = {re.sub(r"[^a-z0-9]", "", c.lower()): c for c in df.columns}
    for c in cands:
        k = re.sub(r"[^a-z0-9]", "", c.lower())
        if k in norm:
            return norm[k]
    raise KeyError(f"none of {cands} in columns {list(df.columns)}")


def slugify(s):
    s = unicodedata.normalize("NFKD", s).encode("ascii", "ignore").decode()
    return re.sub(r"[^a-z0-9]+", "-", s.lower()).strip("-")


def pct(x):
    """Percentile rank 0-100, ties averaged, floored at 1 (METHOD.md step 1)."""
    s = pd.Series(x)
    r = s.rank(method="average")
    n = len(s)
    p = (r - 1) / (n - 1) * 100 if n > 1 else pd.Series([100.0] * n)
    return np.maximum(p.to_numpy(), 1.0)


def pct_matrix(M):
    """Column-wise percentile for a (draws x unis) matrix, average ties, floor 1."""
    from scipy.stats import rankdata
    r = rankdata(M, axis=1, method="average")
    n = M.shape[1]
    return np.maximum((r - 1) / (n - 1) * 100, 1.0)


def index_from(pp10, pp1, p10, w):
    """w = (w_pp10, w_pp1, w_p10). Returns (index, A, B) for the given view weights."""
    a1, a2 = pct(pp10), pct(pp1)
    A = (2.0 * a1 + a2) / 3.0          # pillar A is always PP10:PP1 = 20:10; views change only how A and B combine
    B = pct(p10)
    wa, wb = (w[0] + w[1]), w[2]
    if wb == 0:
        idx = A
    elif wa == 0:
        idx = B
    else:
        idx = np.exp((wa * np.log(A) + wb * np.log(B)) / (wa + wb))
    return idx, A, B


VIEWS = {
    "balanced": (20.0, 10.0, 15.0),
    "quality": (20.0, 10.0, 0.0),
    "strength": (0.0, 0.0, 15.0),
}


def point_ranks(idx):
    """Erratum E1: rank on the published one-decimal score; equal scores share the higher (min) rank."""
    sc = np.round(np.asarray(idx, float), 1)
    order = np.sort(sc)[::-1]
    # rank = 1 + number of universities with a strictly higher published score
    return (np.searchsorted(-order, -sc, side="left") + 1).astype(int)


def simulate(pp10, lb10, ub10, pp1, lb1, ub1, P, view, rng):
    """Erratum E3: callers pass a generator seeded per (field, view) table."""
    n = len(pp10)
    sd10 = np.maximum(ub10 - lb10, 0) / 3.92
    sd1 = np.maximum(ub1 - lb1, 0) / 3.92
    out = np.empty((N_DRAWS, n), dtype=np.int32)
    w0 = np.array(VIEWS[view])
    chunk = 250
    for s in range(0, N_DRAWS, chunk):
        k = min(chunk, N_DRAWS - s)
        d10 = np.clip(pp10 + rng.standard_normal((k, n)) * sd10, 0, None)
        d1 = np.clip(pp1 + rng.standard_normal((k, n)) * sd1, 0, None)
        dp10 = d10 * P
        W = rng.dirichlet(DIRICHLET, size=k) * 45.0          # perturb around 20:10:15
        W = W * (w0 > 0)                                     # views drop the pillars they exclude
        a1, a2, b = pct_matrix(d10), pct_matrix(d1), pct_matrix(dp10)
        wa = W[:, 0:1] + W[:, 1:2]
        A = np.where(wa > 0, (W[:, 0:1] * a1 + W[:, 1:2] * a2) / np.where(wa > 0, wa, 1), 1.0)
        wb = W[:, 2:3]
        idx = np.where(wb == 0, A, np.where(wa == 0, b, np.exp((wa * np.log(A) + wb * np.log(b)) / np.where(wa + wb > 0, wa + wb, 1))))
        order = np.argsort(-idx, axis=1, kind="mergesort")
        r = np.empty_like(order)
        rows = np.arange(k)[:, None]
        r[rows, order] = np.arange(1, n + 1)
        out[s:s + k] = r
    lo = np.percentile(out, 5, axis=0, method="lower").astype(int)
    hi = np.percentile(out, 95, axis=0, method="higher").astype(int)
    return lo, hi


def main():
    df = load()
    c_uni, c_field, c_period = "University", "Field", "Period"
    c_P, c_P10, c_PP10, c_PP10lb, c_PP10ub = "P", "P_top_10", "PP_top_10", "PP_top_10_lb", "PP_top_10_ub"
    c_PP1, c_PP1lb, c_PP1ub = "PP_top_1", "PP_top_1_lb", "PP_top_1_ub"
    c_int, c_oa = "PP_int_collab", "PP_OA"

    unis_meta = json.loads((ROOT / "data" / "universities.json").read_text())
    name_to = {u["name"]: u for u in unis_meta}

    for c in KEEP[7:]:
        df[c] = pd.to_numeric(df[c], errors="coerce")
    frac = df[(df["Core_pubs_only"] == 1) & (df["Frac_counting"] == 1)].copy()
    # Collaboration and OA exist only under full counting (Leiden). Core pubs, full counting, current period:
    full_core = df[(df["Core_pubs_only"] == 1) & (df["Frac_counting"] == 0)].set_index(c_uni)
    # All pubs (core + non-core), full counting: denominator for the retraction rate.
    full_all = df[(df["Core_pubs_only"] == 0) & (df["Frac_counting"] == 0)].set_index(c_uni)

    field_map = {lab: fid for fid, lab in FIELDS}
    frac["fid"] = frac[c_field].map(field_map)
    if frac["fid"].isna().any():
        print("unmapped fields:", frac.loc[frac["fid"].isna(), c_field].unique(), file=sys.stderr)

    periods = sorted(frac[c_period].astype(str).unique())
    assert PERIOD in periods, periods

    cur = frac[frac[c_period].astype(str) == PERIOD]
    unis = sorted(cur.loc[cur["fid"] == "all", c_uni].unique())
    uidx = {n: i for i, n in enumerate(unis)}
    slugs, out_unis = set(), []
    for n in unis:
        m = name_to.get(n, {})
        s = slugify(n)
        while s in slugs:
            s += "-" + slugify(m.get("country", "x"))[:2]
        slugs.add(s)
        out_unis.append({"name": n, "ror": m.get("ror", ""), "country": m.get("country", ""), "slug": s})

    metrics, tables = {}, {}
    for fid, flab in FIELDS:
        sub = cur[cur["fid"] == fid].copy()
        for _, r in sub.iterrows():
            ror = out_unis[uidx[r[c_uni]]]["ror"] if r[c_uni] in uidx else None
            if ror is None:
                continue
            m = {"P": r[c_P], "P10": r[c_P10], "PP10": r[c_PP10], "PP10_lb": r[c_PP10lb], "PP10_ub": r[c_PP10ub],
                 "PP1": r[c_PP1], "PP1_lb": r[c_PP1lb], "PP1_ub": r[c_PP1ub]}
            if fid == "all":
                if r[c_uni] in full_core.index:
                    m["PPint"] = full_core.at[r[c_uni], c_int]
                    m["PPoa"] = full_core.at[r[c_uni], c_oa]
                if r[c_uni] in full_all.index:
                    m["P_full"] = full_all.at[r[c_uni], c_P]
            metrics.setdefault(ror, {})[fid] = {k: (None if pd.isna(v) else float(v)) for k, v in m.items()}
        elig = sub[sub[c_P] >= (OVERALL_MIN_P if fid == "all" else FIELD_MIN_P)]
        elig = elig.dropna(subset=[c_PP10, c_PP1, c_P])
        names = elig[c_uni].to_numpy()
        pp10, pp1, P = elig[c_PP10].to_numpy(float), elig[c_PP1].to_numpy(float), elig[c_P].to_numpy(float)
        lb10, ub10 = elig[c_PP10lb].fillna(elig[c_PP10]).to_numpy(float), elig[c_PP10ub].fillna(elig[c_PP10]).to_numpy(float)
        lb1, ub1 = elig[c_PP1lb].fillna(elig[c_PP1]).to_numpy(float), elig[c_PP1ub].fillna(elig[c_PP1]).to_numpy(float)
        p10 = pp10 * P
        tables[fid] = {}
        for view, w in VIEWS.items():
            idx, A, B = index_from(pp10, pp1, p10, np.array(w))
            rk = point_ranks(idx)
            trng = np.random.default_rng([SEED, [f for f, _ in FIELDS].index(fid), list(VIEWS).index(view)])
            lo, hi = simulate(pp10, lb10, ub10, pp1, lb1, ub1, P, view, trng)
            outside = int(((rk < lo) | (rk > hi)).sum())
            if outside:
                print(f"  {fid}/{view}: {outside} point ranks outside their 5-95% interval; interval widened to include them (E2)", file=sys.stderr)
            lo, hi = np.minimum(lo, rk), np.maximum(hi, rk)
            rows = sorted(
                ([uidx[names[j]], int(rk[j]), int(lo[j]), int(hi[j]), round(float(idx[j]), 1), round(float(A[j]), 1), round(float(B[j]), 1)]
                 for j in range(len(names))), key=lambda x: x[1])
            tables[fid][view] = rows
        print(f"{fid}: {len(names)} universities", file=sys.stderr)

    # trend: point ranks, balanced, all sciences, every period
    trend = {}
    allp = frac[frac["fid"] == "all"]
    for per in periods:
        sub = allp[(allp[c_period].astype(str) == per) & (allp[c_P] >= OVERALL_MIN_P)].dropna(subset=[c_PP10, c_PP1, c_P])
        if len(sub) < 50:
            continue
        pp10, pp1, P = sub[c_PP10].to_numpy(float), sub[c_PP1].to_numpy(float), sub[c_P].to_numpy(float)
        idx, _, _ = index_from(pp10, pp1, pp10 * P, np.array(VIEWS["balanced"]))
        rk = point_ranks(idx)
        for n, r in zip(sub[c_uni].to_numpy(), rk):
            if n in uidx:
                trend.setdefault(out_unis[uidx[n]]["ror"], []).append([per.replace("\u2013", "-"), int(r), int(len(sub))])

    OUT.parent.mkdir(parents=True, exist_ok=True)
    OUT.write_text(json.dumps({
        "meta": {"edition": "2026", "period": PERIOD, "source": "CWTS Leiden Ranking Open Edition 2025 (CC0)",
                 "draws": N_DRAWS, "seed": SEED, "method_version": "1.0" if "--v10" in sys.argv else "1.1", "overall_min_p": OVERALL_MIN_P, "field_min_p": FIELD_MIN_P, "periods": [p.replace("\u2013", "-") for p in periods]},
        "unis": out_unis,
        "fields": [{"id": f, "label": FIELD_LABEL[f]} for f, _ in FIELDS],
        "tables": tables, "metrics": metrics, "trend": trend,
    }, ensure_ascii=False, separators=(",", ":")))
    print(f"wrote {OUT} ({OUT.stat().st_size/1e6:.1f} MB)", file=sys.stderr)


if __name__ == "__main__":
    main()
