"""依頼 348 の 5: 下見の絵 (読むだけ. measure_348.json・compare_348.json から).
  左上: 依頼 347 の 20 本 (高さは全本 7.98 mm). 横 = 向き, 縦 = 爪の面の傾き (送った値). 丸 = 成功・× = 失敗.
  右上: 70 本. 横 = 手先の高さ (送った値), 縦 = |爪の面の傾き|. 青 = 依頼 346・橙 = 依頼 347.
  左下: 70 本の 直す前 (使った) → 直した後 (calc_corr_level) の |爪の面の傾き|. 作れない本は 灰色の × (上の端).
  右下: 直す前と後の 爪の傾き (真下から).

  python3 so101/check_348/preview_348.py   → so101/check_348/preview_348.png  (python3. matplotlib. 字は英字)
"""
import json
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402

HERE = Path(__file__).resolve().parent


def main():
    M = json.loads((HERE / "measure_348.json").read_text())["episodes"]
    C = json.loads((HERE / "compare_348.json").read_text())
    em = C["level_elev_max_deg"]
    fig, ax = plt.subplots(2, 2, figsize=(13, 10))
    a = ax[0, 0]
    for r in M:
        if r["set"] != "347":
            continue
        ok = r["label"] == "success"
        a.scatter(r["yaw"], r["sent"]["jaw_elev"], marker="o" if ok else "x", c="tab:green" if ok else "tab:red", s=60)
        a.annotate(str(r["n"]), (r["yaw"], r["sent"]["jaw_elev"]), fontsize=8, xytext=(3, 3), textcoords="offset points")
    for y in (em, -em):
        a.axhline(y, ls="--", c="gray", lw=0.8)
    a.axhline(0, c="k", lw=0.5)
    a.set_xlabel("block yaw (deg)")
    a.set_ylabel("jaw-face tilt from vertical (deg, sent)")
    a.set_title("request 347: 20 runs (height fixed 7.98 mm). o = OK, x = fail")
    a = ax[0, 1]
    for r in M:
        ok = r["label"] == "success"
        a.scatter(r["sent"]["tcp_z"], abs(r["sent"]["jaw_elev"]), marker="o" if ok else "x",
                  c="tab:blue" if r["set"] == "346" else "tab:orange", s=40)
    a.axhline(em, ls="--", c="gray", lw=0.8)
    a.axvline(10.4, ls=":", c="gray", lw=0.8)
    a.set_xlabel("TCP height (mm, sent)")
    a.set_ylabel("|jaw-face tilt| (deg)")
    a.set_title("70 runs: blue = req 346, orange = req 347. o = OK, x = fail")
    a = ax[1, 0]
    E = C["episodes"]
    for k, r in enumerate(E):
        ok = r["label"] == "success"
        y0 = abs(r["used"]["jaw_elev"])
        col = "tab:green" if ok else "tab:red"
        if "q" in r["new"]:
            y1 = abs(r["new"]["jaw_elev"])
            a.plot([0, 1], [y0, y1], c=col, alpha=0.5, lw=1)
        else:
            a.scatter([1.05], [y0], marker="x", c="gray")
    a.axhline(em, ls="--", c="gray", lw=0.8)
    a.set_xticks([0, 1])
    a.set_xticklabels(["used", f"level (|e|<={em:g})"])
    a.set_ylabel("|jaw-face tilt| (deg)")
    s = C["summary"]
    a.set_title(f"before -> after (green = OK run, red = fail run). made {s['new_solved']}/{s['n']}")
    a = ax[1, 1]
    for r in E:
        if "q" not in r["new"]:
            continue
        ok = r["label"] == "success"
        a.scatter(r["used"]["tool_tilt"], r["new"]["tool_tilt"], marker="o" if ok else "x", c="tab:green" if ok else "tab:red", s=30)
    a.plot([0, 40], [0, 40], c="k", lw=0.5)
    a.set_xlabel("tool tilt from down, used (deg)")
    a.set_ylabel("tool tilt from down, level (deg)")
    a.set_title("tool tilt: level lowers it where the yaw is large")
    fig.tight_layout()
    fig.savefig(HERE / "preview_348.png", dpi=90)


if __name__ == "__main__":
    main()
