"""依頼 380: つかみ直しの道 (recover_377) の「戻る → つかむ所へ下りる → 閉じる」だけを ブロックごとの向きで左へ寄せる
(アームは動かさない. 計算だけ).

依頼 379 で, 失敗した回は つかむ直前の爪の間の点がブロックより右へ +6〜+10 mm (成功は −7〜+4) で,
固定側の爪 (アームの後ろから見て左) がブロックの上の面に乗って下りられなかった. その分を左へ寄せる.
  - 寄せるキー姿勢: 戻った所 (RETRY_ABOVE. 高さだけの外しは MISS_UP) ・GRASP_OPEN・GRASP_CLOSED の 3 つ.
    爪の間の点を −右 (ブロックごとの右 = 根もと → ブロックを時計回りに 90°. 依頼 376 と同じ) へ N mm.
    手先の高さ・爪の傾き (符号つき)・爪の閉じる向きはそのまま (recover_377.Shifter. 機体の IK は使わない).
    つかむ所の高さは変えない.
  - 持ち上げ (LIFT) から先は今の道のまま (寄せた分は持ち上げの 24 コマで戻る). 外す区間も recover_377 のまま.
確かめ (シム. clear_345 と同じ場面):
  grasp_jaws: 下りる区間の 動く爪・固定側の爪とブロックの距離, GRASP_OPEN で ブロックを爪の閉じる向きに動かして
    固定側の爪・開いた動く爪に当たるまでの量 (両方あれば 閉じると両方の爪で挟める)
  sag_path: 依頼 379 の「沈んだ関節」. 肩の指令が下がる区間 (止まったあとも, 次に上がるまで) は肩 +sh°,
    低い所 (手先がブロックの上の高さより 10 mm 以上低いコマ) は肘 +el°. ブロックの上 〜 持ち上げの間だけ.
    符号は 依頼 379 の (実際 − 指令).
"""
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import recover_377 as RC  # noqa: E402
import var_lib_314 as V  # noqa: E402

SAG_GRID = [(sh, el) for sh in (0.0, 3.0, 4.0) for el in (0.0, 2.0, 3.0)]    # 依頼 379: 肩 +3〜4°・肘 +2〜3°
LOW_BELOW_ABOVE_MM = 10.0
GAP_SCAN_MM = 40.0


def make_recover_rise(gmap, res0, rec, bxy, lo, hi):
    """recover_377.make_recover と同じ. 割り振りの recover に rise_mm があれば その本だけ 上がる高さを変える (なければ 50 mm のまま)"""
    rise = rec.get("rise_mm")
    if rise is None:
        return RC.make_recover(gmap, res0, rec, bxy, lo, hi)
    keep = RC.RISE_MM
    RC.RISE_MM = float(rise)
    try:
        return RC.make_recover(gmap, res0, rec, bxy, lo, hi)
    finally:
        RC.RISE_MM = keep


def back_key(frames):
    return "RETRY_ABOVE" if "RETRY_ABOVE" in frames else "MISS_UP"


def shift_grasp(gmap, res, left_mm, bxy, lo, hi):
    """make_recover の答え res の 戻る → つかむ所 → 閉じる を 左へ left_mm 寄せた答え (res は変えない)"""
    out = {"ok": False, "why": "", "pixel": res.get("pixel"), "info": dict(res["info"])}
    if not res.get("ok"):
        out["why"] = res.get("why", "つかみ直しの道が作れない")
        return out
    fr, path0 = res["frames"], np.asarray(res["path"], np.float64)
    names = [k["name"] for k in res["keyframes"]]
    kp = [(n, path0[fr[n]].copy()) for n in names]
    segs = [fr[names[0]]] + [fr[b] - fr[a] for a, b in zip(names, names[1:])]
    sh = RC.Shifter(gmap)
    u, r = RC.block_frame(bxy)
    dxy = -r * float(left_mm)
    kd = dict(kp)
    bk = back_key(fr)
    new, errs = {}, {}
    for k in (bk, "GRASP_OPEN"):
        q5, e = sh.shift(kd[k][:V.J5], dxy, 0.0)
        if q5 is None:
            out["why"] = f"{k} を寄せられない: {e}"
            return out
        new[k], errs[k] = q5, e
    new["GRASP_CLOSED"] = new["GRASP_OPEN"]
    kp2 = [(n, np.r_[new[n], p[V.J5]] if n in new else p) for n, p in kp]
    path, frames = V.assemble(kp2, segs)
    out["path"], out["frames"] = path, frames
    out["keyframes"] = [{"name": k, "frame": int(frames[k]), "pose": np.asarray(p).round(3).tolist()} for k, p in kp2]
    out["phases"] = V.phases_of(frames, len(path))
    g0, z0, s0, j0 = sh.point(kd["GRASP_OPEN"][:V.J5])
    g1, z1, s1, j1 = sh.point(new["GRASP_OPEN"])
    moved = g1 - g0
    d = np.abs(np.diff(path, axis=0))
    sj, sg = float(d[:, :V.J5].max()), float(d[:, 5].max())
    in_range = bool(((path >= lo) & (path <= hi)).all())
    lf = frames["LIFT"]
    same_after = bool(np.abs(path[lf:] - path0[fr["LIFT"]:]).max() < 1e-9) if len(path) == len(path0) else False
    same_before = bool(np.abs(path[:frames[bk] - segs[names.index(bk)] + 1] - path0[:fr[bk] - segs[names.index(bk)] + 1]).max()
                       < 1e-9)
    gi = {"left_mm": float(left_mm), "shift_xy_mm": dxy.round(2).tolist(), "back_key": bk,
          "grasp_point_moved_right_fwd_z_mm": [round(float(moved[:2] @ r), 2), round(float(moved[:2] @ u), 2),
                                               round(float(moved[2]), 2)],
          "tcp_z_change_mm": round(z1 - z0, 3), "tilt_change_deg": round(s1 - s0, 3),
          "jaw_yaw_change_deg": round(float((j1 - j0 + 90) % 180 - 90), 3), "solve_err": errs,
          "grasp_open_before": kd["GRASP_OPEN"][:V.J5].round(3).tolist(), "grasp_open": new["GRASP_OPEN"].round(3).tolist(),
          "same_as_377_before_back": same_before, "same_as_377_from_lift": same_after,
          "grasp_point_mm": g1.round(1).tolist(), "grasp_point_377_mm": g0.round(1).tolist()}
    rinfo = dict(out["info"].get("recover") or {})
    rinfo["grasp_shift_380"] = gi
    out["info"].update({"step_max_joint_deg": round(sj, 2), "step_max_gripper": round(sg, 2), "safe_range_ok": in_range,
                        "safe_margin_min": round(float(min((path - lo).min(), (hi - path).min())), 2),
                        "roll_min_deg": round(float(path[:, 4].min()), 2), "roll_max_deg": round(float(path[:, 4].max()), 2),
                        "recover": rinfo})
    bad = []
    if sj > V.STEP_LIMIT_DEG or sg > V.STEP_LIMIT_GRIP:
        bad.append(f"1 コマの変化 {sj:.2f}°・爪 {sg:.2f} (上限 {V.STEP_LIMIT_DEG:g}°・{V.STEP_LIMIT_GRIP:g})")
    if not in_range:
        j = sorted({V.MOTORS[k] for k in np.where(((path < lo) | (path > hi)).any(0))[0]})
        bad.append(f"安全範囲の外 ({', '.join(j)})")
    if not (same_before and same_after):
        bad.append("寄せる区間の外の道が 377 の道と違う")
    if abs(gi["tcp_z_change_mm"]) > 0.5:
        bad.append(f"つかむ所の高さが変わった ({gi['tcp_z_change_mm']} mm)")
    if bad:
        out["why"] = " / ".join(bad)
        return out
    out["ok"] = True
    return out


def sag_path(gmap, path, frames, sh_deg, el_deg):
    """依頼 379 の沈んだ関節を入れた道 (ブロックの上 〜 持ち上げの間だけ). 肩 = 関節 1・肘 = 関節 2"""
    p = np.asarray(path, np.float64).copy()
    a0, a1 = frames["ABOVE_BLOCK"], frames["LIFT"]
    keys = sorted((f, n) for n, f in frames.items() if a0 <= f <= a1)
    on = False
    for (fa, _), (fb, _) in zip(keys, keys[1:]):
        dsh = path[fb][1] - path[fa][1]
        if dsh < -0.05:
            on = True
        elif dsh > 0.05:
            on = False
        if on:
            p[fa + 1:fb + 1, 1] += sh_deg
    z_above = V.tcp_arm(gmap.chain, gmap._q(path[a0][:V.J5]))[0][2]
    for i in range(a0, a1 + 1):
        z = V.tcp_arm(gmap.chain, gmap._q(path[i][:V.J5]))[0][2]
        if z <= z_above - LOW_BELOW_ABOVE_MM:
            p[i, 2] += el_deg
    return p


class Jaws:
    """固定側の爪 (gripper の体) と 動く爪 (moving_jaw) を分けた距離"""

    def __init__(self):
        import clear_345 as CL
        S = CL.scene()
        self.sc, self.geo = S.sc, S.geo
        m = self.geo.m
        by = lambda body: [g for g in range(m.ngeom) if m.body(int(m.geom_bodyid[g])).name == body]  # noqa: E731
        self.fixed, self.moving = by("gripper"), by("moving_jaw_so101_v1")

    def footprint(self, q, geoms, zmax):
        """姿勢 q で geoms の形の頂点のうち 高さ zmax (mm) より下のもの (腕の座標 mm. 上から見た図用)"""
        import mujoco
        import simreplay_334 as RP
        m, d = self.geo.m, self.geo.d
        self.sc.pose(q)
        pts = []
        for g in geoms:
            if m.geom_type[g] != mujoco.mjtGeom.mjGEOM_MESH or not m.geom_contype[g]:
                continue
            mid = m.geom_dataid[g]
            v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]]
            w = (d.geom_xpos[g] + v @ d.geom_xmat[g].reshape(3, 3).T) * 1000 - RP.D.AXIS_OFF    # シムの世界 → 腕の座標
            pts.append(w[w[:, 2] < zmax])
        return np.concatenate(pts) if pts else np.zeros((0, 3))

    def grasp_jaws(self, path, frames, bxy, yaw):
        """下りる区間 (戻った所 → GRASP_OPEN) の 爪とブロックの距離の最小, GRASP_OPEN で 爪の閉じる向きの すき間"""
        sc, geo = self.sc, self.geo
        bk = back_key(frames)
        sc.block(bxy, yaw)
        fmin, mmin, ffr, mfr = np.inf, np.inf, None, None
        for i in range(frames[bk], frames["GRASP_OPEN"] + 1):
            sc.pose(path[i])
            f, mv = geo.dist(self.fixed, geo.blk), geo.dist(self.moving, geo.blk)
            if f < fmin:
                fmin, ffr = f, i
            if mv < mmin:
                mmin, mfr = mv, i
        sc.pose(path[frames["GRASP_OPEN"]])
        _, a, _ = sc.rp.jaw_dirs()
        sc.pose(path[frames["GRASP_OPEN"]])
        gaps = {}
        for key, geoms, sgn in (("fixed", self.fixed, 1.0), ("moving", self.moving, -1.0)):
            gaps[key] = None
            for s in np.arange(0.0, GAP_SCAN_MM + 1e-9, 0.25):
                sc.block(np.asarray(bxy) + sgn * s * a[:2], yaw)
                if geo.dist(geoms, geo.blk) <= 0.0:
                    gaps[key] = round(float(s), 2)
                    break
        sc.block([1000, 1000], 0)
        u, r = RC.block_frame(bxy)
        pinch = gaps["fixed"] is not None and gaps["moving"] is not None and fmin > 0 and mmin > 0
        return {"fixed_block_min_mm": round(float(fmin), 2), "fixed_frame": int(ffr),
                "moving_block_min_mm": round(float(mmin), 2), "moving_frame": int(mfr),
                "gap_to_fixed_mm": gaps["fixed"], "gap_to_moving_open_mm": gaps["moving"],
                "close_dir_right": round(float(a[:2] @ r), 3), "pinch_ok": bool(pinch)}

    def miss_min(self, path, frames, bxy, yaw):
        """外す区間 (ブロックの上 → 戻るまで) の 腕とブロックの距離の最小 (recover_377.miss_contact と同じ区間)"""
        sc, geo = self.sc, self.geo
        end = frames.get("RETRY_ABOVE", frames["MISS_UP"])
        sc.block(bxy, yaw)
        best, at = np.inf, None
        for i in range(frames["ABOVE_BLOCK"], end + 1):
            sc.pose(path[i])
            v = geo.dist(geo.arm, geo.blk)
            if v < best:
                best, at = v, i
        sc.block([1000, 1000], 0)
        return round(float(best), 2), int(at)
