#!/usr/bin/env python3
"""
Render diagnostic plots for the Expert Binomial (xbinomial) with Scale example.

Usage:
    Place dataset_xbinomial.csv in the same directory, then run:
        python render_xbinomial_plots.py

Requires: pyinla, pandas, numpy, matplotlib
"""

from __future__ import annotations

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pyinla import pyinla

# ── Fit the model ────────────────────────────────────────────────────────────

df = pd.read_csv("dataset_xbinomial.csv")
ntrials = df["ntrials"].to_numpy()
q = df["q"].to_numpy()

model = {
    "response": "y",
    "fixed": ["1", "x"],
}

result = pyinla(model=model, family="xbinomial", data=df, Ntrials=ntrials, scale=q)

# ── Extract quantities ───────────────────────────────────────────────────────

intercept = float(result.summary_fixed.loc["(Intercept)", "mean"])
slope = float(result.summary_fixed.loc["x", "mean"])

eta_hat = intercept + slope * df["x"].to_numpy()
p_hat = 1.0 / (1 + np.exp(-eta_hat))
p_effective = q * p_hat
expected = ntrials * p_effective
residuals = df["y"].to_numpy() - expected

# ── Plot 1: Observed vs expected counts ──────────────────────────────────────

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(expected, df["y"], color="#a78bfa", s=8, edgecolor="none", alpha=0.3)
max_val = max(expected.max(), df["y"].max())
ax.plot([0, max_val], [0, max_val], color="#f97316", linewidth=2.0, linestyle="--", label="y = x (perfect fit)")
ax.set_xlabel("Expected count (N \u00d7 q \u00d7 p)")
ax.set_ylabel("Observed count (y)")
ax.set_title("xBinomial regression: observed vs expected counts")
ax.legend(loc="best")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("binomial-xbinomial-fit.png", dpi=160)
plt.close(fig)

# ── Plot 2: Residuals vs expected counts ─────────────────────────────────────

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(expected, residuals, color="#38bdf8", s=8, edgecolor="none", alpha=0.3)
ax.axhline(0.0, color="#f97316", linewidth=1.6, linestyle="--", label="zero residual")
ax.set_xlabel("Expected count (N \u00d7 q \u00d7 p)")
ax.set_ylabel("Residual (y \u2212 expected)")
ax.set_title("xBinomial regression: residuals vs expected counts")
ax.legend(loc="upper right")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("binomial-xbinomial-residuals.png", dpi=160)
plt.close(fig)

print("Plots saved: binomial-xbinomial-fit.png, binomial-xbinomial-residuals.png")
print(f"Recovered: intercept = {intercept:.4f}, slope = {slope:.4f}")
print(result.summary_fixed)
