"""
From analysis to a deployable model
===================================

An analysis that should run every day has to be reproducible: the same
configuration, the same preprocessing and the same learned regimes. The
:class:`~mvtsa.mlops.AnalysisPipeline` standardizes the data, segments it,
learns recurring regimes from the segments of the training data and labels
new data with them. Every object can be written to a JSON or YAML
configuration; fitted models are saved with checksums, library versions and
a fingerprint of the training data, and a registry keeps their versions and
stages.
"""

import tempfile
from pathlib import Path

import mvtsa as mv
from mvtsa import mlops
from mvtsa import segmentation as sg

# One process with three recurring regimes: the first half is the training
# record, the second half arrives later.
X, cps, states = mv.datasets.make_regime_process(
    n_regimes=3, n_segments=16, length=150, random_state=0
)
half = cps[7]
X_train, X_new, cps_new = X[:half], X[half:], cps[8:] - half
workdir = Path(tempfile.mkdtemp())

# %%
# Configuration as code
# ---------------------
pipe = mlops.AnalysisPipeline(
    sg.BottomUp("normal", n_segments=8, initial_size=15), n_regimes=3
)
cfg = mlops.to_config(pipe)
print(mlops.save_config(pipe, workdir / "pipeline.yaml").read_text())
same = mlops.from_config(cfg)  # an identical, unfitted pipeline
# %%
# Fit, save, register, promote
# ----------------------------
pipe.fit(X_train)
seg = pipe.predict(X_new)
print(
    "regimes of the new data:",
    seg.labels.tolist(),
    "| true regimes:",
    states[8:].tolist(),
)
reg = mlops.ModelRegistry(workdir / "registry")
v1 = reg.register(
    "regimes",
    pipe,
    data=X_train,
    metrics={"covering": 0.97},
    tags={"plant": "demo"},
)
reg.promote("regimes", v1, "production")
print(reg.list()[["name", "version", "stage", "created"]])
production = reg.load("regimes", stage="production")
mv.viz.plot_segmentation(
    X_new,
    production.predict(X_new),
    truth=cps_new,
    title="production model on new data",
)
