"""Energy curves and the Chamfer / normal ladder per object from ../report/knee/<object>.npz and ../report/knee.csv ->
../report/img/knee_<object>.png (|v| running median, energy not yet taken, Chamfer and normal median against atoms)."""
import sys
from pathlib import Path
import numpy as np, pandas as pd
import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
REP = Path(__file__).parent.parent / "report"
K = pd.read_csv(REP / "knee.csv")
for name in sys.argv[1].split(","):
    z = np.load(REP / "knee" / f"{name}.npz")
    fig, ax = plt.subplots(1, 4, figsize=(20, 4.3))
    for cl in [c[:-3] for c in z.files if c.endswith("_rm")]:
        rm, tail, (k, sl) = z[f"{cl}_rm"], z[f"{cl}_tail"], z[f"{cl}_knee"]
        T = np.arange(1, len(rm) + 1)
        l, = ax[0].loglog(T, rm, label=cl)
        ax[1].loglog(T, np.maximum(tail, 1e-12), color=l.get_color(), label=cl)
        g = K[(K.object == name) & (K.cloud == cl)].sort_values("atoms")
        ax[2].semilogx(g.atoms, g["mean"], "o-", color=l.get_color(), label=cl, ms=3)
        ax[3].semilogx(g.atoms, g.n_med, "o-", color=l.get_color(), label=cl, ms=3)
        for a in ax:
            a.axvline(k, color=l.get_color(), ls=":", lw=1)
    ax[0].set(title=f"{name}: |atom value| (running median 64)", xlabel="atoms")
    ax[1].set(title="energy not yet decoded (fraction)", xlabel="atoms")
    ax[2].set(title="Chamfer ×1e-3 (clean mesh)", xlabel="atoms", ylim=(0, None))
    ax[3].set(title="SDF normal median °", xlabel="atoms", ylim=(0, None))
    for a in ax:
        a.grid(True, which="both", alpha=0.3); a.legend(fontsize=7)
    fig.tight_layout(); fig.savefig(REP / "img" / f"knee_{name}.png", dpi=90); plt.close(fig)
    print("saved", name)
