#!/usr/bin/env python3
"""
Render diagnostic plots for the Beta regression with censoring example.

Usage:
    Place dataset_beta_censored.csv in the same directory, then run:
        python render_beta_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_beta_censored.csv")
cens = 0.05

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

control = {
    "family": {
        "beta.censor.value": cens,
    }
}

result = pyinla(model=model, family="beta", data=df, control=control)

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

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

eta_hat = intercept + slope * df["z"].to_numpy()
mu_hat = np.exp(eta_hat) / (1 + np.exp(eta_hat))
residuals = df["y"].to_numpy() - mu_hat

censored = (df["y"] == 0) | (df["y"] == 1)

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

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(mu_hat[~censored], df["y"].to_numpy()[~censored], color="#38bdf8", s=46, edgecolor="white", linewidth=0.4, alpha=0.7, label="uncensored")
ax.scatter(mu_hat[censored], df["y"].to_numpy()[censored], color="#f87171", s=46, edgecolor="white", linewidth=0.4, alpha=0.7, marker="x", label="censored")
ax.plot([0, 1], [0, 1], color="#f97316", linewidth=2, linestyle="--", label="y = x")
ax.set_xlabel("Fitted mean (μ)")
ax.set_ylabel("Observed (y)")
ax.set_title("Beta censored: observed vs fitted mean")
ax.legend(loc="best")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("beta-regression-censored-fit.png", dpi=160)
plt.close(fig)

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

fig, ax = plt.subplots(figsize=(6.2, 4.1))
ax.scatter(mu_hat[~censored], residuals[~censored], color="#a78bfa", s=42, edgecolor="white", linewidth=0.35, alpha=0.7, label="uncensored")
ax.scatter(mu_hat[censored], residuals[censored], color="#f87171", s=42, edgecolor="white", linewidth=0.35, alpha=0.7, marker="x", label="censored")
ax.axhline(0.0, color="#f97316", linewidth=1.6, linestyle="--", label="zero residual")
ax.set_xlabel("Fitted mean (μ)")
ax.set_ylabel("Residual (y − μ)")
ax.set_title("Beta censored: residuals vs fitted mean")
ax.legend(loc="upper right")
ax.grid(alpha=0.25)
fig.tight_layout()
fig.savefig("beta-regression-censored-residuals.png", dpi=160)
plt.close(fig)

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