"""依頼 386: 渡す所の候補 (つかむ所から手先を真上に RAISES mm. 爪は開いたまま・向きは rule_351 の決まりのつかむ所のまま) で
コードの道が作れるか. 計算だけ (アーム・カメラは使わない. 記録・割り振りは読むだけ).

- 割り振り: so101/check_351/plan_351.json の 50 本 (success_v1 の元). 決まりの道は check_377/plan_377.World.rule_path
  (依頼 384 の robust_grid.py と同じ. 外れて戻る道 (detour) は入れない)
- 渡す姿勢: var_lib_314.above_pose(つかむ所, r) (ブロックの上と同じ作り方. 真上に届かなければ根もとの向きへ引く = back_mm).
  作れる = 位置の差 1 mm 未満・向きの差 2° 未満・関節 5 つが安全範囲 (lo・hi) の中
- ずれへの強さ: robust_grid.py と同じ数え方 (置いた所 x・y を −D・0・+D mm, 向きを −A・0・+A° の 27 通り. D 15・A 8)
- そのままの 50 本は, コードの道 (始めの姿勢 → [r ≥ 50] 渡す姿勢 57 コマ / [r < 50] ブロックの上 57 コマ → 渡す姿勢)
  を MuJoCo (clear_345 の場面) に入れて, 腕と机・腕とブロック・爪の先と机 の最小距離 (mm) と 渡す姿勢の爪の間の点 (lib_376) を出す
  /opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python so101/check_386/grid_386.py [D] [A]
"""
import copy
import itertools
import json
import sys
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
sys.path.insert(0, str(SO101 / "check_377"))
sys.path.insert(0, str(SO101 / "check_376"))
PLAN = SO101 / "check_351/plan_351.json"
RAISES = (80.0, 50.0, 30.0, 15.0)
DESCEND = 71            # var_lib_314.TEMPLATE["descend"] (ブロックの上 50 mm → つかむ所)
_W = {}


def _init():
    import plan_377 as P
    plan = json.loads(PLAN.read_text())
    _W["P"], _W["plan"], _W["w"] = P, plan, P.World(plan)


def handoffs(w, grasp5):
    import var_lib_314 as V
    out = {}
    for r in RAISES:
        q, pe, ae, back = V.above_pose(w.chain, grasp5, r)
        inr = bool(((q >= w.lo[:5] - 1e-9) & (q <= w.hi[:5] + 1e-9)).all())
        out[r] = {"ok": bool(pe < 1.0 and ae < 2.0 and inr), "pos_err_mm": round(float(pe), 2), "ang_err_deg": round(float(ae), 2),
                  "back_mm": float(back), "in_range": inr, "q": np.asarray(q).round(3).tolist()}
    return out


def one(args):
    idx, D, A = args
    import sim_330 as S
    import yaw_lib_343 as Y
    w, plan = _W["w"], _W["plan"]
    e0 = plan["episodes"][idx]
    b0 = w.bxy(e0)
    rows = []
    for dx, dy, dyaw in itertools.product((-D, 0, D), (-D, 0, D), (-A, 0, A)):
        e = copy.deepcopy(e0)
        xy = b0 + np.array([dx, dy])
        e["pixel"] = [float(v) for v in S.project_arm([[xy[0], xy[1], Y.BLOCK_MM / 2]], w.cam).reshape(-1)[:2]]
        e["yaw"] = e0["yaw"] + dyaw
        res = w.rule_path(e)
        row = {"d": [dx, dy, dyaw], "rule_ok": bool(res.get("ok")), "why": str(res.get("why"))[:120]}
        if res.get("ok"):
            row["hand"] = handoffs(w, np.asarray(res["info"]["grasp"], float))
            row["grasp"] = res["info"]["grasp"]
            row["above"] = res["info"]["above"]
        rows.append(row)
    nominal = next(r for r in rows if r["d"] == [0, 0, 0])
    return {"index": idx, "pixel": e0["pixel"], "yaw": e0["yaw"], "offset": e0["offset"], "detour": e0["detour"], "rows": rows,
            "nominal": nominal}


def clearance(out):
    """そのままの 50 本: コードの道 (始め → 渡す姿勢) の最小距離と 渡す姿勢の爪の間の点"""
    _init()
    import clear_345 as CL
    import lib_376 as L
    import var_lib_314 as V
    w, plan = _W["w"], _W["plan"]
    arm, cam, _ = L.setup()
    Sc = CL.scene()
    sc, geo = Sc.sc, Sc.geo
    g_open = V.GRIP["ABOVE_BLOCK"]
    for o in out:
        e = plan["episodes"][o["index"]]
        nm = o["nominal"]
        if not nm["rule_ok"]:
            continue
        b = w.bxy(e)
        start = np.r_[V.HOME[:5] + np.asarray(e["offset"], float), V.HOME[5]]
        above50 = np.r_[nm["above"], g_open]
        o["clear"] = {}
        for r in RAISES:
            h = nm["hand"][r]
            if not h["ok"]:
                continue
            tgt = np.r_[h["q"], g_open]
            if r >= 50:
                kp, segs = [("S", start), ("H", tgt)], [0, V.TEMPLATE["to_above"]]
            else:
                kp, segs = [("S", start), ("A", above50), ("H", tgt)], [0, V.TEMPLATE["to_above"], int(round(DESCEND * (50 - r) / 50))]
            path, fr = V.assemble(kp, segs)
            sc.block(list(b), e["yaw"])
            d_tab, d_blk, d_jaw = [], [], []
            for q in path:
                sc.pose(q)
                d_tab.append(geo.dist(geo.arm, geo.table))
                d_blk.append(geo.dist(geo.arm, geo.blk))
                d_jaw.append(geo.dist(geo.jaw, geo.table))
            sc.block([1000, 1000], 0)
            c = arm.center(tgt)
            rel = L.rel(c[None], b)[0]
            o["clear"][r] = {"frames": len(path), "arm_table_min": round(float(min(d_tab)), 1), "arm_block_min": round(float(min(d_blk)), 1),
                             "jaw_table_min": round(float(min(d_jaw)), 1), "center_mm": c.round(1).tolist(),
                             "center_rel_right_fwd_z": rel.round(1).tolist(), "step_max_deg": round(float(np.abs(np.diff(path[:, :5], axis=0)).max()), 2)}
        # つかむ所の爪の間の点 (高さの目安)
        cg = arm.center(np.r_[nm["grasp"], V.GRIP["GRASP_OPEN"]])
        o["grasp_center_mm"] = cg.round(1).tolist()
        print(o["index"] + 1, {r: (v["arm_table_min"], v["arm_block_min"], v["center_rel_right_fwd_z"]) for r, v in o["clear"].items()},
              flush=True)


def dump(doc):
    (HERE / "grid_386.json").write_text(json.dumps(doc, ensure_ascii=False, default=lambda x: x.tolist() if hasattr(x, "tolist") else str(x)) + "\n")


def main(argv):
    if argv and argv[0] == "--clear-only":         # 数え上げは済み (grid_386.json) で, 距離の確かめだけやり直す
        doc = json.loads((HERE / "grid_386.json").read_text())
        for o in doc["episodes"]:
            for x in o["rows"] + [o["nominal"]]:
                if "hand" in x:
                    x["hand"] = {float(k): v for k, v in x["hand"].items()}
        clearance(doc["episodes"])
        dump(doc)
        return
    D = float(argv[0]) if argv else 15.0
    A = float(argv[1]) if len(argv) > 1 else 8.0
    n = len(json.loads(PLAN.read_text())["episodes"])
    with ProcessPoolExecutor(8, initializer=_init) as ex:
        out = []
        for o in ex.map(one, [(i, D, A) for i in range(n)]):
            nm = o["nominal"]
            print(o["index"] + 1, "決まりの道", nm["rule_ok"],
                  {r: v["ok"] for r, v in nm.get("hand", {}).items()},
                  {r: sum(1 for x in o["rows"] if x["rule_ok"] and x["hand"][r]["ok"]) for r in RAISES}, flush=True)
            out.append(o)
    doc = {"plan": str(PLAN), "D_mm": D, "A_deg": A, "raises_mm": list(RAISES), "episodes": out}
    dump(doc)
    clearance(out)
    dump(doc)


if __name__ == "__main__":
    main(sys.argv[1:])
