"""
Registry, model card and drift monitoring
=========================================

An equation in production needs the same care as any model. This example
registers a soft-sensor equation with its data fingerprint and validity domain
(:class:`~eqdisco.mlops.ModelRegistry`), writes its model card
(:class:`~eqdisco.mlops.ModelCard`; Mitchell et al., 2019), and then monitors a
stream of new data in which the process slowly drifts: the population stability
index of the inputs, the share of samples outside the training box, and a
Page--Hinkley test on the residuals (:class:`~eqdisco.mlops.DriftMonitor`).
"""

import tempfile

import matplotlib.pyplot as plt
import numpy as np

import eqdisco as eq
from eqdisco.mlops import DriftMonitor, ModelCard, ModelRegistry

rng = np.random.default_rng(1)
X = np.column_stack([rng.uniform(300, 360, 300), rng.uniform(1, 5, 300)])
y = 0.02 * X[:, 0] * np.sqrt(X[:, 1]) + rng.normal(0, 0.05, 300)
model = eq.SymbolicRegressor(population_size=200, generations=20, functions=("add", "sub", "mul", "sqrt"), feature_names=["T", "p"], random_state=0).fit(X, y)

# %%
# Registry and model card
# -----------------------
reg = ModelRegistry(tempfile.mkdtemp())
v = reg.register("quality-sensor", model.equation_, X=X, y=y, tags={"unit": "reactor 2"})
reg.promote("quality-sensor", v, "production")
card = ModelCard(model.equation_, "quality-sensor", intended_use="estimate product quality every minute", X=X, y=y)
print(reg.list())
print(card.to_markdown()[:600])
# %%
# Monitoring a drifting process
# -----------------------------
monitor = DriftMonitor(reg.load("quality-sensor", stage="production"), X, y)
reports = []
for week in range(12):
    drift = max(0, week - 5) * 6.0  # the temperature rises after week 5
    Xw = np.column_stack([rng.uniform(300, 360, 100) + drift, rng.uniform(1, 5, 100)])
    yw = 0.02 * Xw[:, 0] * np.sqrt(Xw[:, 1]) * (1 + 0.004 * max(0, week - 5)) + rng.normal(0, 0.05, 100)
    reports.append(monitor.check(Xw, yw))
print([r["status"] for r in reports])
fig, axs = plt.subplots(1, 2, figsize=(10, 3.4))
psi = [r["features"]["T"]["psi"] for r in reports]
out = [r["outside_domain"] for r in reports]
sdr = [r["residual_sd_ratio"] for r in reports]
weeks = np.arange(12)
colors = {"ok": "#009E73", "warning": "#E69F00", "retrain": "#D55E00"}
axs[0].bar(weeks, psi, color=[colors[r["status"]] for r in reports])
thr_w, thr_r = reports[0]["psi_thresholds"]  # 95 % and 99 % points for 300 vs 100 samples
axs[0].axhline(thr_w, color="#E69F00", ls="--", lw=0.8)
axs[0].axhline(thr_r, color="#D55E00", ls="--", lw=0.8)
axs[0].set_xlabel("week")
axs[0].set_ylabel("PSI of T (bar color: status)")
axs[1].plot(weeks, out, "o-", color="#285780", label="share outside training box")
axs[1].plot(weeks, sdr, "s-", color="#D55E00", label="residual sd / reference")
axs[1].set_xlabel("week")
axs[1].legend(frameon=False, fontsize=8)
fig.tight_layout()
eq.viz.plot_drift(reports[-1])

# %%
# Parameter study: the Page--Hinkley threshold
# --------------------------------------------
lams = [2, 5, 10, 20, 40]
delay = []
for lam in lams:
    mon = DriftMonitor(model.equation_, X, y, ph_lambda=lam)
    Xs = np.column_stack([rng.uniform(300, 360, 400), rng.uniform(1, 5, 400)])
    ys = 0.02 * Xs[:, 0] * np.sqrt(Xs[:, 1]) + rng.normal(0, 0.05, 400)
    ys[200:] += 0.1  # a sudden offset at sample 200
    alarm, at = mon.page_hinkley(ys - model.equation_.predict(Xs))
    delay.append((at - 200) if alarm and at is not None and at >= 200 else np.nan)
print("Page-Hinkley threshold", lams, "detection delay", delay)
fig, ax = plt.subplots(figsize=(4.5, 3))
ax.plot(lams, delay, "o-", color="#285780")
ax.set_xlabel("Page-Hinkley threshold $\\lambda$")
ax.set_ylabel("detection delay (samples)")
plt.show()
