#!/usr/bin/env python3
"""依頼 405: 空のあとの道の順 (開いてから上がる = 依頼の形 / 上がってから開く) を 外し方ごとにシムで比べる (計算だけ・アームなし).
場所2〜5 の目印 (今日の実機と同じガードの値) で rule_401 の道を作り, つかむ所 (GRASP_OPEN) から 爪の間の点を 奥・手前・右・左へ 10・15・20 mm,
上へ 10・20 mm ずらした所で 空で閉じた (爪 0.74) とし, switch_405 と同じ ガード (clear_after held=False) を当てる.
「上がってから開く」は 閉じたまま 渡す所の高さへ上がり (同じコマ数), 上で開く (10 コマ). 同じガードを当てる (開く区間は上なので 腕と机も見る).

  SO101_VAR_ROLL_RANGE=-67,58 R401_PUSH_LIMIT_MM=-12 R401_PUSH_WINDOW_MM=-12 $P so101/check_405/open_order_405.py → open_order_405.md・.json
"""
import json
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
for p in (HERE.parent, HERE.parent / "check_401", HERE.parent / "check_392", HERE.parent / "check_399", HERE.parent / "ideal_var", HERE):
    if str(p) not in sys.path:
        sys.path.insert(0, str(p))
import run_rule401 as RR  # noqa: E402
import switch_405 as SW  # noqa: E402

MISS = [("奥", 1, 0, 0), ("手前", -1, 0, 0), ("右", 0, 1, 0), ("左", 0, -1, 0)]
MM = (10.0, 15.0, 20.0)
UP = (10.0, 20.0)


def paths(W, b, q5, open_g, z_above):
    q_up, dz, back = SW.rise_pose(W, q5, z_above)
    n_rise = max(1, int(np.ceil(dz / SW.RISE_MM_PER_FRAME))) if dz > 0 else 1
    h6 = np.r_[q5, 0.74]
    a, fa = SW.segment(h6, [("OPENED", np.r_[q5, open_g], SW.OPEN_FRAMES), ("RISEN", np.r_[q_up, open_g], n_rise)])
    c, fc = SW.segment(h6, [("RISEN", np.r_[q_up, 0.74], n_rise), ("OPENED2", np.r_[q_up, open_g], SW.OPEN_FRAMES)])
    return (a, fa), (c, fc)


def main():
    plan, lo, hi = RR.load_plan(RR.PLAN)
    W = RR.world()
    jt = plan.get("jaw_table_min_mm", -11.0)
    rows = []
    for place in (2, 3, 4, 5):
        e = plan["episodes"][place - 1]
        b, info = RR.prepare(W, plan, place, lo, hi, None, (e["pixel"][0], e["pixel"][1], 0.0), False, ("conflict",), False)
        fr = b["v"]["frames"]
        g5 = b["path"][fr["GRASP_OPEN"]][:5]
        a6 = b["path"][fr["ABOVE_BLOCK"]]
        _, z_above, _, _ = W.sh.point(a6[:5])
        u = np.asarray(b["bxy"]) / np.linalg.norm(b["bxy"])
        r = np.array([u[1], -u[0]])
        cases = [("つかむ所", 0.0, np.zeros(2), 0.0)]
        for name, sf, sr, _ in MISS:
            for mm in MM:
                cases.append((f"{name} {mm:g}", mm, (sf * u + sr * r) * mm, 0.0))
        for mm in UP:
            cases.append((f"上 {mm:g}", mm, np.zeros(2), mm))
        for name, mm, dxy, dz in cases:
            q, err = W.sh.shift(g5, dxy, dz)
            if q is None:
                rows.append({"place": place, "case": name, "solved": False})
                continue
            (pa, fa), (pc, fc) = paths(W, b, q, a6[5], z_above)
            ca = SW.clear_after(pa, fa, b["bxy"], b["yaw"], False, jt)
            fc2 = dict(fc, OPENED=0)            # 上がってから開く: 全区間で 腕と机 (始め = 閉じた所) を見る
            cc = SW.clear_after(pc, fc2, b["bxy"], b["yaw"], False, jt)
            rows.append({"place": place, "case": name, "solved": True, "open_first_ok": ca["ok"], "open_first_why": ca["why"],
                         "open_first": ca["dist"], "rise_first_ok": cc["ok"], "rise_first_why": cc["why"], "rise_first": cc["dist"]})
            print(place, name, ca["ok"], cc["ok"], ca["why"][:80], flush=True)
    (HERE / "open_order_405.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1) + "\n")
    L = ["# 依頼 405: 空のあとの道の順 (開いてから上がる / 上がってから開く) を 外し方ごとに (open_order_405.py が書いた)", "",
         "場所2〜5 の目印・rule_401 の道 (今日のガードの値)・つかむ所から 爪の間の点をずらした所で 空で閉じたとする. ○ = switch_405 のガードを通る", "",
         "| 外し方 | " + " | ".join(f"場所{p} 開→上 | 場所{p} 上→開" for p in (2, 3, 4, 5)) + " |", "|---|" + "---|---|" * 4]
    names = [x["case"] for x in rows if x["place"] == 2]
    for n in names:
        cells = []
        for p in (2, 3, 4, 5):
            x = next(y for y in rows if y["place"] == p and y["case"] == n)
            if not x["solved"]:
                cells += ["解けない", "解けない"]
                continue
            fa = x["open_first"]
            cells += [("○" if x["open_first_ok"] else "×") + f" (ブロック {fa.get('arm_block')})",
                      ("○" if x["rise_first_ok"] else "×") + f" (ブロック {x['rise_first'].get('arm_block')})"]
        L.append(f"| {n} | " + " | ".join(cells) + " |")
    n_ok = {k: sum(1 for x in rows if x.get(k)) for k in ("open_first_ok", "rise_first_ok")}
    L += ["", f"通った数 (全 {sum(1 for x in rows if x['solved'])}): 開いてから上がる {n_ok['open_first_ok']}・上がってから開く {n_ok['rise_first_ok']}",
          "かっこは 腕 (爪・手首・カメラ) とシムのブロックの最小距離 mm (負は重なり)"]
    (HERE / "open_order_405.md").write_text("\n".join(L) + "\n")
    print("\n".join(L))


if __name__ == "__main__":
    main()
