"""Business Schools 2026, method v1.0 (METHOD-business.md, registered 2026-10-10).

Inputs : data/biz/universe.json, careers_*.json, research_utd.json, alumni_lists.json, ppp.json
Output : data/processed/business_v1.json
"""
import json, math, re, sys
from pathlib import Path

import numpy as np

ROOT = Path(__file__).resolve().parent.parent
B = ROOT / "data" / "biz"
OUT = ROOT / "data" / "processed" / "business_v1.json"
SEED, N_DRAWS = 20261011, 2000
W = {"salary": 25, "employed": 10, "founders": 15, "f500": 5, "billionaires": 5, "gmat": 10, "accept": 5, "research_total": 15, "research_per_fac": 10}
PILLAR = {"salary": "careers", "employed": "careers", "founders": "alumni", "f500": "alumni", "billionaires": "alumni",
          "gmat": "selectivity", "accept": "selectivity", "research_total": "research", "research_per_fac": "research"}
CURRENCY = {"United States": "USD", "United Kingdom": "GBP", "France": "EUR", "Spain": "EUR", "Italy": "EUR", "Germany": "EUR", "Netherlands": "EUR",
            "Ireland": "EUR", "Belgium": "EUR", "Portugal": "EUR", "Switzerland": "CHF", "Canada": "CAD", "Australia": "AUD", "Singapore": "SGD",
            "Hong Kong": "HKD", "China": "CNY", "India": "INR", "Japan": "JPY", "South Korea": "KRW", "Denmark": "DKK", "Sweden": "SEK",
            "Norway": "NOK", "Brazil": "BRL", "Mexico": "MXN", "South Africa": "ZAR", "United Arab Emirates": "AED", "Israel": "ILS",
            "Chile": "CLP", "Colombia": "COP", "Peru": "PEN", "Argentina": "ARS", "Taiwan": "TWD", "Thailand": "THB", "Malaysia": "MYR"}


def load(name):
    p = B / f"{name}.json"
    return json.loads(p.read_text()) if p.exists() else {}


uni = load("universe")
schools = uni if isinstance(uni, list) else uni.get("schools", uni.get("entries", []))
schools = [s for s in schools if s.get("full_time_mba") is not False]
ids = [s["id"] for s in schools]
n = len(schools)
DATA = {}
ALIAS = {"salary_base": "median_base_salary", "employed_3m": "employed_3mo_pct"}     # round-1 tracks used two id styles
# later files win: round-1 files first, then gap-fill rounds
FILES = (sorted(B.glob("careers_*.json"), key=lambda f: ("_gap_" in f.name, f.name)) + [B / "class_profile_gap.json", B / "research_utd.json", B / "alumni_lists.json"]
         + sorted(B.glob("r3_*.json")))     # round 3 (gap fill for core metrics) wins
for f in FILES:
    if f.exists():
        for sid, rec in json.loads(f.read_text()).get("by_school", {}).items():
            for k, v in rec.items():
                k = ALIAS.get(k, k)
                if isinstance(v, dict) and isinstance(v.get("value"), (int, float)):
                    if k == "class_size" and f.name == "class_profile_gap.json" and k in DATA.get(sid, {}):
                        continue
                    DATA.setdefault(sid, {})[k] = v
                elif k == "currency" and isinstance(v, str):
                    DATA.setdefault(sid, {})["_currency"] = v
PPP = load("ppp").get("by_country", {})


GMATC = json.loads((B / "gmat_concordance.json").read_text()) if (B / "gmat_concordance.json").exists() else None


def _year_ok(v):   # Amendment 1.5: classes before 2023 are not used; pooled figures take their earliest class (5.3)
    ys = [int(y) for y in re.findall(r"(20\d\d)", str(v.get("year", "")))]
    return not ys or min(ys) >= 2023


EMP_BASIS = {k: v["basis"] for k, v in load("employment_basis").get("by_school", {}).items()}   # Amendment 5.2


def _employment_ok(v, sid=None):   # Amendment 1.2: offers *received* only -> not used
    if sid in EMP_BASIS:
        return EMP_BASIS[sid] == "accepted"
    basis = str(v.get("basis", "")).lower()
    note = str(v.get("note", "")).lower()
    if basis in ("offers", "offer", "received"):
        return False
    if re.search(r"received (at least one |a )?(job )?offer|offers? received|\(offer, not acceptance\)|offer, not acceptance", note) and not re.search(r"\d+(\.\d+)?% (acceptances|accepted)|accepted (an )?offers?|acceptances", note.split("(")[0]):
        return False
    return True


CLASS_METRICS = {"median_base_salary", "employed_3mo_pct", "class_size", "gmat_avg", "acceptance_rate"}   # Amendment 2.1


def val(sid, m):
    v = DATA.get(sid, {}).get(m)
    if not v or (m in CLASS_METRICS and not _year_ok(v)):
        return None
    if m == "employed_3mo_pct" and not _employment_ok(v, sid):
        return None
    return float(v["value"])


def _interp(table, x):
    ks = sorted(int(k) for k in table)
    if x <= ks[0]:
        return table[str(ks[0])]
    if x >= ks[-1]:
        return table[str(ks[-1])]
    for a, b in zip(ks, ks[1:]):
        if a <= x <= b:
            pa, pb = table[str(a)], table[str(b)]
            return pa + (pb - pa) * (x - a) / (b - a)


_ED = r"(focus|classic|10th|legacy|previous edition|previous version)"
GMAT_ED_OVERRIDE = {k: (float(v["value"]), v["edition"]) for k, v in load("gmat_editions").get("by_school", {}).items()}   # Amendment 3.5
for _sid, _v in load("gmat_editions").get("by_school", {}).items():
    if _v.get("use"):
        DATA.setdefault(_sid, {})["gmat_avg"] = _v["use"]


def gmat_edition(sid):
    """Edition of the recorded GMAT value (Amendment 1.1 as refined by Amendment 3.1):
    'focus' / 'classic' when the source states it, 'either' when it doesn't (scored as both readings)."""
    v = DATA.get(sid, {}).get("gmat_avg")
    if not v:
        return None
    x = float(v["value"])
    if sid in GMAT_ED_OVERRIDE and GMAT_ED_OVERRIDE[sid][0] == x:   # reviewed reading for this exact value
        return GMAT_ED_OVERRIDE[sid][1]
    note = (str(v.get("edition", "")) + " " + str(v.get("note", ""))).lower()
    note = re.sub(r"20[05]\s*[-–]\s*80[05]", " ", note)                       # scale ranges
    note = re.sub(r"edition (unknown|not stated|unspecified)|scale (not stated|not labelled|ambiguous)|\(?(classic|focus) (vs\.?|or) (classic|focus)\)?", " ", note)
    # a collector's or checker's guess is not the source stating the edition
    note = re.sub(r"(likely|probably|presumably|almost certainly)[^.;)]{0,30}?" + _ED + r"|" + _ED + r" (scale |edition )?assumed", " ", note)
    # mentions of the OTHER figure ("GMAT Focus average 676", "Focus avg 584", "classic median was 730") are removed
    def other(mm):
        nums = [int(t) for t in re.findall(r"\b([4-8]\d\d)\b", mm.group(0))]
        return " " if nums and all(t != int(x) for t in nums) else mm.group(0)
    note = re.sub(_ED + r"(?:(?!" + _ED + r")[^0-9;.,]){0,28}?\b[4-8]\d\d\b", other, note)
    note = re.sub(r"\b[4-8]\d\d\b[^a-z0-9;]{0,6}" + _ED, other, note)
    hits = [(mm.start(), "focus" if mm.group(1) == "focus" else "classic") for mm in re.finditer(_ED, note)]
    if hits:
        return min(hits)[1]
    if "bloomberg" in note:
        return "focus"            # Amendment 1.1: Bloomberg 2026-27 profiles report Focus-scale figures
    if x >= 700:
        return "classic"          # Amendment 3.1: a Focus class average this high would sit above the 99th percentile
    return "either"


def gmat_pct(sid, rng=None):   # Amendment 1.1: GMAT as GMAC concordance percentile
    v = DATA.get(sid, {}).get("gmat_avg")
    if not v or not GMATC or not _year_ok(v):
        return None
    x = float(v["value"])
    ed = gmat_edition(sid)
    if ed is None:
        return None
    if ed == "either":            # Amendment 3.1: mean of both readings (the Monte Carlo draws one at random)
        if rng is not None:
            return _interp(GMATC["focus_pct" if rng.random() < 0.5 else "classic_pct"], x)
        return (_interp(GMATC["focus_pct"], x) + _interp(GMATC["classic_pct"], x)) / 2
    return _interp(GMATC["focus_pct" if ed == "focus" else "classic_pct"], x)


def currency_of(sid, country):
    c = DATA.get(sid, {}).get("_currency")
    if not c:
        rec = DATA.get(sid, {}).get("median_base_salary") or {}
        mm = re.search(r"\b(USD|GBP|EUR|CHF|CAD|AUD|SGD|HKD|CNY|INR|JPY|KRW|DKK|SEK|NOK|BRL|MXN|ZAR|AED|ILS)\b", (rec.get("note") or "") + " " + str(rec.get("currency", "")))
        c = mm.group(1) if mm else CURRENCY.get(country, "USD")
    return c


INTL = {}
for _f in sorted(B.glob("intl_share_*.json")):
    for _sid, _rec in json.loads(_f.read_text()).get("by_school", {}).items():
        if isinstance(_rec.get("intl_share_pct"), dict) and isinstance(_rec["intl_share_pct"].get("value"), (int, float)):
            INTL[_sid] = float(_rec["intl_share_pct"]["value"]) / 100


def price_country(s):   # Hong Kong schools are filed under China but price and pay in HKD
    return "Hong Kong" if (s.get("city") or "") == "Hong Kong" else s["country"]


def intl_share(s):
    """Amendment 4.2: published international share of the class; else the country median; US schools need none."""
    if s["id"] in INTL:
        return INTL[s["id"]], True
    peers = [INTL[x["id"]] for x in schools if x["id"] in INTL and price_country(x) == price_country(s)]
    return (float(np.median(peers)) if peers else 0.0), False


def salary_ppp(s):
    """Median base salary in US$, converted at PPP for the home-national share of the class and at market rates for
    the international share (Amendment 4): salary_lcu / (PPP^(1-f) * FX^f)."""
    v = val(s["id"], "median_base_salary")
    if v is None:
        return None
    if s["country"] == "United States":
        return v
    p = PPP.get(price_country(s)) or {}
    if not p.get("ppp_lcu_per_intl_usd") or not p.get("fx_lcu_per_usd"):
        return None
    rec = DATA.get(s["id"], {}).get("median_base_salary") or {}
    cur = (rec.get("currency") or currency_of(s["id"], price_country(s)) or "").upper()
    if "PPP" not in cur and cur not in ("USD", CURRENCY.get(price_country(s))):
        print(f"warning: {s['id']} salary currency {cur} is neither USD nor local; treated as local", file=sys.stderr)
    if "PPP" in cur:            # published in PPP dollars: back to local currency at home PPP (Amendment 4.3)
        lcu = v * p["ppp_lcu_per_intl_usd"]
    elif cur == "USD":          # reported in USD: back to local currency at the market rate
        lcu = v * p["fx_lcu_per_usd"]
    else:
        lcu = v
    f, _ = intl_share(s)
    return lcu / (p["ppp_lcu_per_intl_usd"] ** (1 - f) * p["fx_lcu_per_usd"] ** f)


def z(arr, impute=False, rng=None):
    """z-scores from the published values; Amendment 2.3: a missing value is estimated at the 25th percentile
    of the published ones (Monte Carlo: uniform between the 10th percentile and the median)."""
    a = np.array([np.nan if x is None else x for x in arr], float)
    m = ~np.isnan(a)
    out = np.full(len(a), np.nan)
    if m.sum() >= 3 and np.nanstd(a) > 0:
        mu, sd = np.nanmean(a), np.nanstd(a)
        out[m] = np.clip((a[m] - mu) / sd, -2.5, 2.5)
        if impute and (~m).any():
            q10, q25, q50 = np.percentile(a[m], [10, 25, 50])
            est = np.full((~m).sum(), q25) if rng is None else rng.uniform(q10, q50, (~m).sum())
            out[~m] = np.clip((est - mu) / sd, -2.5, 2.5)
    return out


CLS_PUB = [val(i, "class_size") for i in ids]
_cv = [c for c in CLS_PUB if c]
MEDIAN_CLASS = float(np.median(_cv)) if _cv else 300.0
CLS_Q25, CLS_Q75 = (float(np.percentile(_cv, 25)), float(np.percentile(_cv, 75))) if _cv else (MEDIAN_CLASS, MEDIAN_CLASS)


def class_sizes(rng=None):   # Amendment 2.3: missing class size -> median (MC: uniform 25th-75th percentile)
    return [c if c else (MEDIAN_CLASS if rng is None else float(rng.uniform(CLS_Q25, CLS_Q75))) for c in CLS_PUB]
LISTS = {"founders": "pitchbook_mba_founders", "f500": "f500_ceo_mbas", "billionaires": "billionaire_mbas"}
cut_meta = load("alumni_lists").get("cutoffs", {})


def _cutoff(metric):
    vals = [val(i, metric) for i in ids if val(i, metric)]
    c = cut_meta.get(metric)
    return float(c) if isinstance(c, (int, float)) else (min(vals) if vals else 1.0)


def list_lograte(metric, rng=None, cls=None):
    """log(count) - 1/2 log(class size) (Amendment 2.4); unlisted schools follow main-method Amendments 4.3 / 9.1
    (size-neutral floor, capped at the lowest listed school)."""
    cls = cls or class_sizes(rng)
    cut = _cutoff(metric)
    listed = [math.log(val(i, metric)) - 0.5 * math.log(c) for i, c in zip(ids, cls) if val(i, metric) and c]
    cap = min(listed) if listed else None
    out = []
    for i, c in zip(ids, cls):
        if not c:
            out.append(None); continue
        x = val(i, metric)
        if x:
            out.append(math.log(x) - 0.5 * math.log(c)); continue
        lo = -0.5 * math.log(MEDIAN_CLASS)
        hi = math.log(cut) - 0.5 * math.log(c)
        if cap is not None:
            hi = min(hi, cap)
        lo = min(lo, hi)
        out.append((lo + hi) / 2 if rng is None else rng.uniform(lo, hi))
    return out


UTD_CUT = None


def research_vals(rng=None):
    global UTD_CUT
    tot = [val(i, "utd_score") for i in ids]
    listed = [t for t in tot if t]
    UTD_CUT = min(listed) if listed else 1.0
    lt = []
    for t in tot:
        if t:
            lt.append(math.log(t))
        else:   # UTD lists every school with >= 1 article in the 24 journals; absent = below the smallest listed score
            lt.append(math.log(UTD_CUT / 2) if rng is None else rng.uniform(math.log(UTD_CUT / 4), math.log(UTD_CUT)))
    fac = [val(i, "faculty_size") for i in ids]
    pf = [(l - math.log(f)) if (f and l is not None) else None for l, f in zip(lt, fac)]
    return lt, pf


SAL_PUB = [salary_ppp(s) for s in schools]
EMP_PUB = [val(i, "employed_3mo_pct") for i in ids]
GMAT_PUB = [gmat_pct(i) for i in ids]
ACC_PUB = [val(i, "acceptance_rate") for i in ids]
FAC_PUB = [val(i, "faculty_size") for i in ids]
# what each school actually publishes (estimates never count toward eligibility)
PUB = {"salary": [x is not None for x in SAL_PUB], "employed": [x is not None for x in EMP_PUB],
       "founders": [bool(val(i, "pitchbook_mba_founders")) for i in ids], "f500": [bool(val(i, "f500_ceo_mbas")) for i in ids],
       "billionaires": [bool(val(i, "billionaire_mbas")) for i in ids], "gmat": [x is not None for x in GMAT_PUB],
       "accept": [x is not None for x in ACC_PUB], "research_total": [bool(val(i, "utd_score")) for i in ids],
       "research_per_fac": [bool(f and val(i, "utd_score")) for i, f in zip(ids, FAC_PUB)]}
ESTIMATED = {"salary", "employed", "gmat"}   # Amendment 2.3
DROPPED = set()                              # Amendment 2.2, filled once eligibility is known


def metrics(rng=None):
    rt, rpf = research_vals(rng)
    cls = class_sizes(rng)
    acc = [(-math.log(a if a > 1 else a * 100)) if a else None for a in ACC_PUB]   # accept % or fraction; lower is better
    Z = {
        "salary": z([math.log(x) if x else None for x in SAL_PUB], True, rng),
        "employed": z(EMP_PUB, True, rng),
        "founders": z(list_lograte("pitchbook_mba_founders", rng, cls)),
        "f500": z(list_lograte("f500_ceo_mbas", rng, cls)),
        "billionaires": z(list_lograte("billionaire_mbas", rng, cls)),
        "gmat": z(GMAT_PUB if rng is None else [gmat_pct(i, rng) for i in ids], True, rng),
        "accept": z(acc),
        "research_total": z(rt),
        "research_per_fac": z(rpf),
    }
    for m in DROPPED:
        Z[m] = np.full(n, np.nan)
    return Z


def score(Z, w):
    M = np.vstack([Z[k] for k in W])
    wv = np.array([w[k] for k in W], float)[:, None]
    av = ~np.isnan(M)
    return (np.where(av, M, 0) * wv).sum(0) / np.maximum((av * wv).sum(0), 1e-9)


eligible = np.array([(PUB["salary"][k] or PUB["employed"][k]) and any(PUB[m][k] for m in W if PILLAR[m] != "careers") for k in range(n)])
COVERAGE = {m: round(sum(PUB[m][k] for k in range(n) if eligible[k]) / max(1, eligible.sum()), 3) for m in W}
DROPPED.update(m for m in W if COVERAGE[m] < 0.25)   # Amendment 2.2, applied as written (5.1)
Z0 = metrics()
F0 = score(Z0, W)
idx = np.where(eligible)[0]
disp = np.full(n, np.nan)
disp[idx] = np.round(100 * (F0[idx] - F0[idx].min()) / (F0[idx].max() - F0[idx].min()), 1)
rank = np.full(n, 0)
for k in idx:
    rank[k] = 1 + int((disp[idx] > disp[k]).sum())

rng = np.random.default_rng(SEED)
alpha = np.array([W[k] for k in W], float) / 2.5
sims = np.empty((N_DRAWS, len(idx)), int)
for d in range(N_DRAWS):
    wd = dict(zip(W, rng.dirichlet(alpha)))
    Fd = score(metrics(rng), wd)[idx]
    order = np.argsort(-Fd, kind="mergesort")
    r = np.empty(len(idx), int)
    r[order] = np.arange(1, len(idx) + 1)
    sims[d] = r
lo = np.percentile(sims, 5, axis=0, method="lower").astype(int)
hi = np.percentile(sims, 95, axis=0, method="higher").astype(int)

rows, excluded = [], []
pos = {k: j for j, k in enumerate(idx)}
for k, s in enumerate(schools):
    if not eligible[k]:
        excluded.append({"id": s["id"], "school": s["school"], "country": "Hong Kong SAR, China" if s.get("city") == "Hong Kong" else s["country"], "reason": "needs a careers metric and one other pillar"})
        continue
    j = pos[k]
    pill = {}
    for p in ("careers", "alumni", "selectivity", "research"):
        ms = [m for m in W if PILLAR[m] == p and not np.isnan(Z0[m][k])]
        pill[p] = round(sum(Z0[m][k] * W[m] for m in ms) / sum(W[m] for m in ms), 3) if ms else None
    rows.append({**{x: s.get(x) for x in ("id", "school", "parent_university", "ror", "country", "city", "ft_mba_2026_rank", "utd_rank", "bbw_rank", "website")},
                 "rank": int(rank[k]), "lo": int(min(lo[j], rank[k])), "hi": int(max(hi[j], rank[k])), "score": float(disp[k]),
                 "pillars": pill, "z": {m: (None if np.isnan(Z0[m][k]) else round(float(Z0[m][k]), 2)) for m in W},
                 "estimated": sorted([m for m in ESTIMATED if not PUB[m][k]] + (["class_size"] if not CLS_PUB[k] else [])),
                 "salary_ppp": salary_ppp(s), "gmat_pct": GMAT_PUB[k], "gmat_edition": gmat_edition(s["id"]) if GMAT_PUB[k] is not None else None, "raw": {m: DATA.get(s["id"], {}).get(m) for m in
                     ("median_base_salary", "employed_3mo_pct", "class_size", "gmat_avg", "acceptance_rate", "utd_score", "utd_rank", "faculty_size",
                      "pitchbook_mba_founders", "f500_ceo_mbas", "billionaire_mbas")}})
for r in rows:   # display label matches the university ranking
    if r.get("city") == "Hong Kong" or (r["country"] == "China" and next((x for x in schools if x["id"] == r["id"]), {}).get("city") == "Hong Kong"):
        r["country"] = "Hong Kong SAR, China"
rows.sort(key=lambda r: (r["rank"], r["school"]))
OUT.write_text(json.dumps({"meta": {"method": "business v1.0 + Amendments 1-5", "n": len(rows), "weights": W, "seed": SEED, "draws": N_DRAWS,
                                    "median_class": MEDIAN_CLASS, "utd_cutoff": UTD_CUT, "coverage": COVERAGE, "dropped": sorted(DROPPED),
                                    "excluded": excluded}, "rows": rows},
                          ensure_ascii=False, indent=0, default=str))
for r in rows[:30]:
    print(f"{r['rank']:>3} [{r['lo']:>3}-{r['hi']:<3}] {r['score']:5.1f}  {r['school'][:46]} ({r['country']})")
print(f"ranked {len(rows)}, excluded {len(excluded)}", file=sys.stderr)
