#!/usr/bin/env python3
"""
Render diagnostic plots for the Student's t-distribution (observation scale) example.

Usage:
    Place dataset_t_scale.csv in the same directory, then run:
        python render_t_scale_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_t_scale.csv")

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

control = {
    "compute": {
        "dic": True,
        "cpo": True,
        "mlik": True,
    }
}

result = pyinla(
    model=model, family="T", data=df,
    scale=df["scale"].to_numpy(), control=control,
)

# ── 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()
mu_hat = eta_hat  # identity link
residuals = df["y"].to_numpy() - mu_hat

# ── Plot 1: Observed vs fitted ──────────────────────────────────────────────

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(mu_hat, df["y"], color="#38bdf8", s=32, edgecolor="white", linewidth=0.4, alpha=0.65)
lims = [min(mu_hat.min(), df["y"].min()), max(mu_hat.max(), df["y"].max())]
ax.plot(lims, lims, color="#f97316", linewidth=2.0, linestyle="--", label="y = x")
ax.set_xlabel("Fitted value (η)")
ax.set_ylabel("Observed (y)")
ax.set_title("t-distribution (scale): observed vs fitted")
ax.legend(loc="best")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("t-scale-fit.png", dpi=160)
plt.close(fig)

# ── Plot 2: Residuals vs fitted ─────────────────────────────────────────────

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(mu_hat, residuals, color="#a78bfa", s=32, edgecolor="white", linewidth=0.35, alpha=0.65)
ax.axhline(0.0, color="#f97316", linewidth=1.6, linestyle="--", label="zero residual")
ax.set_xlabel("Fitted value (η)")
ax.set_ylabel("Residual (y − η)")
ax.set_title("t-distribution (scale): residuals vs fitted")
ax.legend(loc="upper right")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("t-scale-residuals.png", dpi=160)
plt.close(fig)

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