"""The Python script of the PhosKinTime video tutorial (docs/Documentation/app.md): a fit of the synthetic example with
``phoskintime.networkmodel.api`` and in-silico experiments with ``phoskintime.networkmodel.sim``. The example's data are invented curves, so
neither the fit nor the predictions mean anything.

    pixi run python docs/assets/video/example_library.py <new folder>
"""
import sys
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt

from phoskintime.networkmodel import api, sim


def main():
    folder = Path(sys.argv[1]).expanduser()
    conf = api.write_example(folder, n_starts=2)                       # synthetic inputs and a config.toml
    report = api.validate_inputs(conf)                                 # everything a run reads, without fitting
    print("inputs ok:", report.ok, "| warnings:", len(report.warnings))

    run_dir = api.run(conf, log=folder / "run.log")                    # one network-model run (sbmlsim fit)
    tables = api.read_results(run_dir)
    print(tables["multistart"].head().T.to_string(header=False))

    model = sim.load(run_dir)                                          # the run's SBML model
    print("kinases:", model.kinases, "| genes:", model.genes)

    times = (0, 4, 8, 15, 30, 60, 120, 240, 480)                       # minutes
    plain = sim.Experiment("sustained", times=times)
    washout = sim.Experiment("K1 80 % inhibited, 15-120 min", times=times,
                             perturbations=(sim.Perturbation("inhibit", "K1", fraction=0.8, t_on=15, t_off=120),))
    no_edge = sim.Experiment("edge K2 -> B Y_4 removed", times=times,
                             perturbations=(sim.Perturbation("remove_edge", kinase="K2", site="B_Y_4"),))
    result = api.simulate(model, [plain, washout, no_edge], out=folder / "washout.pke.zip")
    dose = api.simulate(model, preset="dose_response", target="K1", times=times, out=folder / "dose_K1.pke.zip")

    site = "X_B_Y_4"                                                   # phosphorylated B at Y_4
    t = result.trajectories.query("variable == @site")
    print(t.pivot(index="time", columns="scenario", values="fold_change").round(3).to_string())

    fig, axes = plt.subplots(1, 2, figsize=(10, 3.6), sharey=True)
    for ax, res, title in ((axes[0], result, "interventions"), (axes[1], dose, "dose response of K1")):
        for name, s in res.trajectories.query("variable == @site").groupby("scenario", sort=False):
            ax.plot(s["time"], s["fold_change"], marker="o", ms=3, label=name)
        ax.set(title=title, xlabel="time (min)")
        ax.legend(fontsize=7)
    axes[0].set_ylabel("B Y_4, fold change")
    fig.suptitle("Synthetic example: invented curves, not data")
    fig.tight_layout()
    fig.savefig(folder / "experiments.png", dpi=130)
    print("written:", ", ".join(sorted(p.name for p in folder.glob("*.p*"))))


if __name__ == "__main__":          # the network build starts worker processes, which import this file again
    main()
