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

Usage:
    Place dataset_t_regression.csv in the same directory, then run:
        python render_t_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_regression.csv")

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

result = pyinla(model=model, family="T", data=df)

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

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

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(eta_hat, df["y"], color="#38bdf8", s=46, edgecolor="white",
           linewidth=0.4, alpha=0.7, label="observations")
max_val = max(eta_hat.max(), df["y"].max())
min_val = min(eta_hat.min(), df["y"].min())
ax.plot([min_val, max_val], [min_val, max_val], color="#f97316", linewidth=2.0,
        linestyle="--", label="y = x (perfect fit)")
ax.set_xlabel("Fitted value (η)")
ax.set_ylabel("Observed (y)")
ax.set_title("Student's t regression: observed vs fitted")
ax.legend(loc="best")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("t-regression-fit.png", dpi=160)
plt.close(fig)

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

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(eta_hat, residuals, color="#a78bfa", s=42, edgecolor="white",
           linewidth=0.35)
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("Student's t regression: residuals")
ax.legend(loc="upper right")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("t-regression-residuals.png", dpi=160)
plt.close(fig)

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