"""Extra analyses for the Game 4 paper.
1) Fisher's exact test on Spurs 3PT, first half vs second half.
2) Knicks shooting by half.
3) Monte Carlo 'what if': replay Spurs' second-half shots at normal make rates, hold everything else fixed.
Usage: python3 extras_g4.py shots.csv freethrows.csv
"""
import sys
import numpy as np
import pandas as pd
from scipy import stats

shots = pd.read_csv(sys.argv[1])
fts = pd.read_csv(sys.argv[2])
for df in (shots, fts):
    df["secs"] = df.clock.str.split(":").apply(lambda x: int(x[0]) * 60 + float(x[1]))
    df["t"] = (df.quarter - 1) * 720 + (720 - df.secs)
    df["h2"] = df.quarter >= 3
shots["zone"] = np.where(shots.shot_type == "3pt", "three", np.where(shots.distance_ft <= 3, "rim", "mid"))
shots["make"] = shots.result == "make"
shots = shots.sort_values("t").reset_index(drop=True)
prev_t = shots.groupby("team").t.shift()
prev_r = shots.groupby("team").result.shift()
shots["putback"] = (shots.t - prev_t <= 3) & (prev_r == "miss")

# 1) Fisher, full halves
s3 = shots[(shots.team == "SAS") & (shots.zone == "three")]
a = [int(s3[~s3.h2].make.sum()), int((~s3[~s3.h2].make).sum())]
b = [int(s3[s3.h2].make.sum()), int((~s3[s3.h2].make).sum())]
odds, p1 = stats.fisher_exact([a, b], alternative="greater")
_, p2 = stats.fisher_exact([a, b])
print(f"SAS 3PT 1H {a[0]}/{sum(a)} vs 2H {b[0]}/{sum(b)}: OR {odds:.2f}, one-sided p {p1:.4f}, two-sided p {p2:.4f}")
fg = shots[shots.team == "SAS"]
a = [int(fg[~fg.h2].make.sum()), int((~fg[~fg.h2].make).sum())]
b = [int(fg[fg.h2].make.sum()), int((~fg[fg.h2].make).sum())]
odds, p1 = stats.fisher_exact([a, b], alternative="greater")
print(f"SAS FG 1H {a[0]}/{sum(a)} vs 2H {b[0]}/{sum(b)}: OR {odds:.2f}, one-sided p {p1:.6f}")

# 2) Knicks by half
for team in ["NYK", "SAS"]:
    for h in [False, True]:
        s = shots[(shots.team == team) & (shots.h2 == h)]
        f = fts[(fts.team == team) & (fts.h2 == h)]
        pts = int((s.make * np.where(s.zone == "three", 3, 2)).sum() + (f.result == "make").sum())
        z = {zn: f"{int(s[s.zone == zn].make.sum())}/{int((s.zone == zn).sum())}" for zn in ["rim", "mid", "three"]}
        print(f"{team} {'2H' if h else '1H'}: pts {pts}, FG {int(s.make.sum())}/{len(s)} ({s.make.mean():.1%}), "
              f"zones {z}, FT {int((f.result == 'make').sum())}/{len(f)}, shots {len(s)}")

# 3) Monte Carlo
rng = np.random.default_rng(2026)
N = 200_000
sas2 = shots[(shots.team == "SAS") & shots.h2 & ~shots.putback]
ft2 = int(((fts.team == "SAS") & fts.h2 & (fts.result == "make")).sum())
sas1_pts = 76
nyk_final = 107
actual_fg2 = int((sas2.make * np.where(sas2.zone == "three", 3, 2)).sum())
print(f"\nSim pool: {len(sas2)} SAS 2H non-putback shots; actual FG pts from them {actual_fg2}; 2H FT pts {ft2}")
val = np.where(sas2.zone == "three", 3, 2)
h1 = shots[(shots.team == "SAS") & ~shots.h2]
scenarios = {
    "League-average rates (approx.)": {"rim": 0.65, "mid": 0.42, "three": 0.36},
    "Spurs' own first-half rates": {zn: h1[h1.zone == zn].make.mean() for zn in ["rim", "mid", "three"]},
    "Spurs' actual second-half rates": {zn: sas2[sas2.zone == zn].make.mean() for zn in ["rim", "mid", "three"]},
}
for name, r in scenarios.items():
    p = sas2.zone.map(r).values
    makes = rng.random((N, len(p))) < p
    pts2 = makes @ val + ft2
    total = sas1_pts + pts2
    win = (total < nyk_final).mean() + 0.5 * (total == nyk_final).mean()
    print(f"{name}: rates { {k: round(v, 3) for k, v in r.items()} }, mean SAS 2H pts {pts2.mean():.1f} "
          f"(5-95%: {np.percentile(pts2, 5):.0f}-{np.percentile(pts2, 95):.0f}), P(NYK win) {win:.4f}")
# sensitivity on league-average
for rim, mid, three in [(0.60, 0.40, 0.34), (0.70, 0.45, 0.38)]:
    p = sas2.zone.map({"rim": rim, "mid": mid, "three": three}).values
    makes = rng.random((N, len(p))) < p
    total = sas1_pts + makes @ val + ft2
    win = (total < nyk_final).mean() + 0.5 * (total == nyk_final).mean()
    print(f"sensitivity rim {rim} mid {mid} three {three}: P(NYK win) {win:.4f}")

# Histogram of simulated Spurs second-half points at approx. league-average rates
p = sas2.zone.map({"rim": 0.65, "mid": 0.42, "three": 0.36}).values
makes = np.random.default_rng(7).random((N, len(p))) < p
pts2 = makes @ val + ft2
lo_, hi_ = int(pts2.min()), int(pts2.max())
counts = np.bincount(pts2.astype(int))
print("HIST", ",".join(f"{{pts:{k},share:{counts[k]/N*100:.3f}}}" for k in range(20, 76) if k < len(counts)))
print("P(<=30)", (pts2 <= 30).mean(), "P(31 tie)", (pts2 == 31).mean(), "mean", pts2.mean())
