"""Logistic regression on Game 4 (2026 Finals) shot data.
Question: did Spurs shooting fall after halftime even after accounting for shot type/distance?
Logit fit by Newton-Raphson (statsmodels unavailable); SEs from the inverse Hessian.
"""
import sys
import numpy as np
import pandas as pd
from scipy import stats

d = pd.read_csv(sys.argv[1])
d["make"] = (d.result == "make").astype(float)
d["second_half"] = (d.quarter >= 3).astype(float)
d["three"] = (d.shot_type == "3pt").astype(float)
d["rim"] = ((d.shot_type == "2pt") & (d.distance_ft <= 3)).astype(float)
d["mid"] = ((d.shot_type == "2pt") & (d.distance_ft > 3)).astype(float)


def logit(y, X, names):
    b = np.zeros(X.shape[1])
    for _ in range(100):
        p = 1 / (1 + np.exp(-X @ b))
        g = X.T @ (y - p)
        H = X.T @ (X * (p * (1 - p))[:, None])
        step = np.linalg.solve(H, g)
        b += step
        if np.max(np.abs(step)) < 1e-10:
            break
    p = 1 / (1 + np.exp(-X @ b))
    H = X.T @ (X * (p * (1 - p))[:, None])
    se = np.sqrt(np.diag(np.linalg.inv(H)))
    ll = np.sum(y * np.log(p) + (1 - y) * np.log(1 - p))
    z = b / se
    out = pd.DataFrame({
        "coef": b, "se": se, "z": z, "p": 2 * stats.norm.sf(np.abs(z)),
        "OR": np.exp(b), "OR_lo": np.exp(b - 1.96 * se), "OR_hi": np.exp(b + 1.96 * se),
    }, index=names)
    return out, ll


def run(team):
    s = d[d.team == team]
    y = s.make.values
    print(f"\n===== {team}: n={len(s)} shots, FG {int(y.sum())}/{len(s)} =====")
    print(s.groupby("second_half").apply(lambda g: pd.Series({
        "FG": f"{int(g.make.sum())}/{len(g)}", "FG%": round(g.make.mean(), 3),
        "rim_share": round(g.rim.mean(), 3), "mid_share": round(g.mid.mean(), 3),
        "three_share": round(g.three.mean(), 3), "avg_dist": round(g.distance_ft.mean(), 1)}),
        include_groups=False).to_string())
    print("3PT by half:", s[s.three == 1].groupby("second_half").make.agg(["sum", "count"]).to_dict())

    one = np.ones(len(s))
    # Model A: half only
    XA = np.column_stack([one, s.second_half])
    A, llA = logit(y, XA, ["const", "second_half"])
    # Model B: half + shot zone (baseline = rim, 0-3 ft)
    XB = np.column_stack([one, s.second_half, s.mid, s.three])
    B, llB = logit(y, XB, ["const", "second_half", "mid_2pt", "three"])
    # Model B minus half, for a likelihood-ratio test of the half effect
    XB0 = np.column_stack([one, s.mid, s.three])
    _, llB0 = logit(y, XB0, ["const", "mid_2pt", "three"])
    lr = 2 * (llB - llB0)
    print("\nModel A (make ~ second_half):\n", A.round(4).to_string())
    print("\nModel B (make ~ second_half + zone):\n", B.round(4).to_string())
    print(f"LR test for second_half in B: chi2={lr:.3f}, df=1, p={stats.chi2.sf(lr, 1):.4f}")
    # McFadden pseudo R2 vs null
    ybar = y.mean()
    ll0 = len(y) * (ybar * np.log(ybar) + (1 - ybar) * np.log(1 - ybar))
    print(f"McFadden R2 model B: {1 - llB / ll0:.3f}")

    # Shot-quality-adjusted expectation: first-half zone rates applied to second-half shots
    h1, h2 = s[s.second_half == 0], s[s.second_half == 1]
    rates = {z: h1[h1[z] == 1].make.mean() for z in ["rim", "mid", "three"]}
    exp_makes = sum(h2[z].sum() * r for z, r in rates.items())
    print("1H zone rates:", {k: round(v, 3) for k, v in rates.items()})
    print("2H zone counts/makes:", {z: (int(h2[h2[z] == 1].make.sum()), int(h2[z].sum())) for z in ["rim", "mid", "three"]})
    print(f"2H expected makes at 1H zone rates: {exp_makes:.1f} vs actual {int(h2.make.sum())}")
    # Same with Model B predicted at second_half=0 (pooled zone effects)
    pred = 1 / (1 + np.exp(-(np.column_stack([np.ones(len(h2)), np.zeros(len(h2)), h2.mid, h2.three]) @ B.coef.values)))
    print(f"2H expected makes from model B with half effect switched off: {pred.sum():.1f}")
    return B


run("SAS")
run("NYK")

# Pooled model: zone + team-specific half effects, to test whether the Spurs' change differs from the Knicks'
y = d.make.values
sas = (d.team == "SAS").astype(float).values
X = np.column_stack([np.ones(len(d)), sas, d.mid, d.three, d.second_half * sas, d.second_half * (1 - sas)])
P, llP = logit(y, X, ["const", "SAS", "mid_2pt", "three", "2H_x_SAS", "2H_x_NYK"])
print("\n===== Pooled (both teams) =====\n", P.round(4).to_string())
diff = P.coef["2H_x_SAS"] - P.coef["2H_x_NYK"]
# covariance for the contrast
p = 1 / (1 + np.exp(-X @ P.coef.values))
V = np.linalg.inv(X.T @ (X * (p * (1 - p))[:, None]))
c = np.array([0, 0, 0, 0, 1, -1])
se = np.sqrt(c @ V @ c)
print(f"Contrast SAS 2H effect minus NYK 2H effect: {diff:.3f} (se {se:.3f}), z={diff/se:.2f}, p={2*stats.norm.sf(abs(diff/se)):.4f}")
