"""Classify every collected request by the frozen rules in protocol-r1.json and compute every measure the design names.

Reads the collected outcomes (tools/collect.py) and the selection; writes results/summary.json and data/requests.csv.
No network. Deterministic: the bootstrap seeds are the protocol's.
Usage: python3 -I -B tools/analyze.py <outcomes.json>
"""
import csv
import hashlib
import json
import random
import statistics
import sys
from datetime import datetime, timedelta
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
PROTO = json.loads((ROOT / "protocol-r1.json").read_text(encoding="utf-8"))
H = PROTO["horizon_days"]                       # 1095
LAND = PROTO["landmark"]["day"]                 # 90
SEED = PROTO["within_project"]["bootstrap"]["seed"]
NBOOT = PROTO["within_project"]["bootstrap"]["n"]
CLASSES = [c["id"] for c in PROTO["outcome_classes_in_order"]]


def ts(s):
    return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ") if s else None


def days(a, b):
    return (ts(b) - ts(a)).total_seconds() / 86400


def tie(project, number):
    return hashlib.sha256(f"{project}#{number}".encode("utf-8")).hexdigest()


def classify(r):
    """One outcome class per request, applied in the protocol's order. Returns (class, evidence)."""
    if r["state"] == "OPEN":
        return "open", "state open"
    closes = [t for t in r["timeline"] if t["type"] == "closed"]
    last = max(closes, key=lambda t: t["at"]) if closes else None
    if last and last["closer"] == "PullRequest" and last["closer_merged"]:
        return "shipped", "closed by a merged pull request"
    if last and last["closer"] == "Commit":
        return "shipped", "closed by a commit"
    if r["state_reason"] == "COMPLETED":
        lim = ts(r["closed_at"]) + timedelta(days=7)
        for t in r["timeline"]:
            if (t["type"] == "xref_pr" and t["same_repo"] and t["merged"] and t["merged_at"]
                    and ts(r["created_at"]) <= ts(t["merged_at"]) <= lim):
                return "shipped", "closed as completed after a merged pull request that references it"
    if last and last["by_bot"]:
        return "closed_by_automation", "closed by an automation account"
    if r["state_reason"] == "NOT_PLANNED":
        return "declined", "closed as not planned"
    if r["state_reason"] == "DUPLICATE":
        return "duplicate", "closed as duplicate"
    return "closed_done_unlinked", "closed as completed, no linked merged change"


def boot(per_project, rng):
    """Mean of per-project values and a 95% percentile interval from resampling projects."""
    vals = list(per_project)
    m = statistics.fmean(vals)
    bs = sorted(statistics.fmean(rng.choice(vals) for _ in vals) for _ in range(NBOOT))
    return {"mean": m, "lo": bs[int(0.025 * NBOOT)], "hi": bs[int(0.975 * NBOOT) - 1], "projects": len(vals)}


def share(rows, key="ship3"):
    return sum(r[key] for r in rows) / len(rows) if rows else None


def within(rows_by_project, key, rng):
    diffs = {}
    for p, rows in rows_by_project.items():
        top = [r for r in rows if 1 <= r["rank"] <= 5]
        bot = [r for r in rows if 16 <= r["rank"] <= 20]
        if top and bot:
            diffs[p] = share(top, key) - share(bot, key)
    out = boot(diffs.values(), rng)
    out["top_share"] = share([r for rs in rows_by_project.values() for r in rs if r["rank"] <= 5], key)
    out["bottom_share"] = share([r for rs in rows_by_project.values() for r in rs if r["rank"] >= 16], key)
    return out, diffs


def main(outcomes_path):
    sel = json.loads((ROOT / "data" / "selection.json").read_text(encoding="utf-8"))["projects"]
    meta = {p["full_name"]: p for p in sel}
    col = json.loads(Path(outcomes_path).read_text(encoding="utf-8"))
    rows = []
    for r in col["requests"]:
        cls, why = classify(r)
        open_days = None if r["state"] == "OPEN" else days(r["created_at"], r["closed_at"])
        ship_days = open_days if cls == "shipped" else None
        early = sum(1 for t in r["early_vote_times"] if days(r["created_at"], t) <= LAND)
        rows.append({"project": r["project"], "rank": r["rank"], "number": r["number"], "opened": r["created_at"][:10],
                     "votes": r["votes_now"], "votes_at_selection": r["votes_at_selection"], "early_votes_90d": early,
                     "early_capped": len(r["early_vote_times"]) >= 60 and early >= 60,
                     "outcome": cls, "evidence": why, "days_to_close": open_days, "days_to_ship": ship_days,
                     "ship3": cls == "shipped" and ship_days <= H,
                     "ship3_sens": cls in ("shipped", "closed_done_unlinked") and open_days is not None and open_days <= H,
                     "closed_by_90": open_days is not None and open_days <= LAND,
                     "star_rank": meta[r["project"]]["star_rank"]})
    n = len(rows)
    # deciles over all requests: votes ascending, ties by the fixed hash
    order = sorted(rows, key=lambda r: (r["votes"], tie(r["project"], r["number"])))
    for i, r in enumerate(order):
        r["decile"] = i * 10 // n + 1
    deciles = []
    for d in range(1, 11):
        g = [r for r in rows if r["decile"] == d]
        shipped_days = sorted(r["days_to_ship"] for r in g if r["outcome"] == "shipped")
        curve = [sum(1 for x in shipped_days if x <= t) / len(g) for t in range(0, H + 1)]
        deciles.append({"decile": d, "n": len(g), "votes_min": min(r["votes"] for r in g),
                        "votes_max": max(r["votes"] for r in g), "votes_median": statistics.median(r["votes"] for r in g),
                        "ship3": share(g), "ship3_sens": share(g, "ship3_sens"),
                        "ship_ever": sum(r["outcome"] == "shipped" for r in g) / len(g),
                        "median_days_to_ship": statistics.median(shipped_days) if shipped_days else None,
                        "outcomes": {c: sum(r["outcome"] == c for r in g) for c in CLASSES},
                        "curve": [round(v, 5) for v in curve]})
    by_p = {}
    for r in rows:
        by_p.setdefault(r["project"], []).append(r)
    rng = random.Random(SEED)
    wp, wp_diffs = within(by_p, "ship3", rng)
    wp_sens, _ = within(by_p, "ship3_sens", rng)
    # by star third of the projects (stars descending in the selection order)
    ranks = sorted({meta[p]["star_rank"] for p in by_p})
    third = {sr: min(3, i * 3 // len(ranks) + 1) for i, sr in enumerate(ranks)}
    wp_third = {}
    for k in (1, 2, 3):
        sub = {p: rs for p, rs in by_p.items() if third[meta[p]["star_rank"]] == k}
        wp_third[str(k)], _ = within(sub, "ship3", rng)
    # speed
    def med_ship(lo, hi, rs=rows):
        v = [r["days_to_ship"] for r in rs if r["outcome"] == "shipped" and lo <= r["rank"] <= hi]
        return {"n": len(v), "median_days": statistics.median(v) if v else None}
    speed = {"ranks_1_5": med_ship(1, 5), "ranks_16_20": med_ship(16, 20)}
    def med_dec(ds):
        v = [r["days_to_ship"] for r in rows if r["outcome"] == "shipped" and r["decile"] in ds]
        return {"n": len(v), "median_days": statistics.median(v) if v else None}
    speed_thirds = {"deciles_1_3": med_dec({1, 2, 3}), "deciles_4_7": med_dec({4, 5, 6, 7}), "deciles_8_10": med_dec({8, 9, 10})}
    # 90-day landmark, within project
    land_diffs = {}
    land_rows = 0
    land_hi, land_lo = [], []
    for p, rs in by_p.items():
        el = [r for r in rs if not r["closed_by_90"]]
        land_rows += len(el)
        el.sort(key=lambda r: (r["early_votes_90d"], tie(r["project"], r["number"])))
        k = len(el) // 2
        if k == 0:
            continue
        lo, hi = el[:k], el[-k:]
        land_diffs[p] = share(hi) - share(lo)
        land_hi += hi
        land_lo += lo
    land = boot(land_diffs.values(), rng)
    land["eligible_requests"] = land_rows
    land["more_early_votes_share"] = share(land_hi)
    land["fewer_early_votes_share"] = share(land_lo)
    land["half_size"] = len(land_hi)
    land["median_early_votes_more"] = statistics.median(r["early_votes_90d"] for r in land_hi)
    land["median_early_votes_fewer"] = statistics.median(r["early_votes_90d"] for r in land_lo)
    land["early_votes_zero_share"] = sum(1 for r in rows if not r["closed_by_90"] and r["early_votes_90d"] == 0) / land_rows
    # totals
    totals = {c: sum(r["outcome"] == c for r in rows) for c in CLASSES}
    ship3_all = sum(r["ship3"] for r in rows)
    # per project (lookup)
    projects = []
    for p in sel:
        rs = sorted(by_p.get(p["full_name"], []), key=lambda r: r["rank"])
        projects.append({"project": p["full_name"], "star_rank": p["star_rank"], "requests": len(rs),
                         "ship3": sum(r["ship3"] for r in rs), "shipped_ever": sum(r["outcome"] == "shipped" for r in rs),
                         "open": sum(r["outcome"] == "open" for r in rs),
                         "top_minus_bottom": wp_diffs.get(p["full_name"])})
    summary = {"n_requests": n, "n_projects": len(by_p), "missing": col["missing"], "totals": totals,
               "ship3": {"count": ship3_all, "share": ship3_all / n},
               "ship3_sens_share": sum(r["ship3_sens"] for r in rows) / n,
               "shipped_ever_share": totals["shipped"] / n,
               "deciles": deciles, "within_project": wp, "within_project_sens": wp_sens,
               "within_project_by_star_third": wp_third, "speed_by_rank": speed, "speed_by_decile_thirds": speed_thirds,
               "landmark_90d": land, "projects": projects,
               "vote_change": {"median_now": statistics.median(r["votes"] for r in rows),
                               "median_at_selection": statistics.median(r["votes_at_selection"] for r in rows),
                               "changed_rank_inputs": sum(r["votes"] != r["votes_at_selection"] for r in rows)}}
    (ROOT / "results").mkdir(exist_ok=True)
    (ROOT / "results" / "summary.json").write_text(json.dumps(summary, indent=1) + "\n", encoding="utf-8")
    cols = ["project", "rank", "number", "opened", "votes", "early_votes_90d", "decile", "outcome", "days_to_close",
            "days_to_ship", "ship3"]
    with open(ROOT / "data" / "requests.csv", "w", encoding="utf-8", newline="") as f:
        w = csv.writer(f)
        w.writerow(cols)
        for r in sorted(rows, key=lambda r: (r["star_rank"], r["rank"])):
            w.writerow([r[c] if not isinstance(r[c], float) else f"{r[c]:.1f}" for c in cols])
    print(f"requests {n}, projects {len(by_p)}, missing {len(col['missing'])}")
    print("totals", totals)
    print(f"shipped within 3y {ship3_all} ({ship3_all / n:.1%}); sensitivity {summary['ship3_sens_share']:.1%}")
    print(f"within project top5 - ranks16-20: {wp['mean']:+.3f} [{wp['lo']:+.3f}, {wp['hi']:+.3f}] over {wp['projects']}")
    print(f"landmark 90d: {land['mean']:+.3f} [{land['lo']:+.3f}, {land['hi']:+.3f}] over {land['projects']}")
    print("deciles ship3", [round(d["ship3"], 3) for d in deciles])
    print("speed", speed)


if __name__ == "__main__":
    main(sys.argv[1])
