"""依頼 401 の 2: 今の決まり (rule_351) と rule_401 (案 C を 腕の動きの予想 dir_s で下げ量を解いた形) を,
腕の動きの予想 (arm_response_400) を通した道と 指令どおりの道 (依頼 399 の「沈みなし」) の両方で シム (MuJoCo. clear_345 と同じ場面) で比べる.
アームは動かさない. 計算だけ. 既にあるファイルは変えない (読む・import するだけ).
数字は KIOXIA lab/so101_Log12/401/ に json で置く (記録・台帳・データセットは書き換えない).

  plan   : plan_351.json の 50 か所. か所ごとに 下げ量・指令と予想のすき間・沈み最大 (肩 +4・肘 +3) の 爪と机 と,
           ずれ 19 通り + 固定側へ 8 mm の 形 (挟める. 依頼 399 の 2-4 と同じ) → sweep_401_plan.json
  places : 実機の 5 か所 (so101f の最初のコマの中央値の置き方. check_399/closes_399.json. 依頼 399 の places_399 と同じ作り方).
           道が作れない所は 近い置き方を探す (place_search) → sweep_401_places.json
形 (shape): 下りる間に どちらの爪もブロックに重ならない かつ つかむ所で動く爪を閉じていくとブロックに当たる かつ
  ブロックを閉じる向きに動かすと固定側の爪に当たる (lib_399.World.pinch と同じ). 予想の道では
  固定側は ブロックの上 → 予想のつかむ所 (爪が 20 を割ったコマ), 動く爪は ブロックの上 → GRASP_OPEN の最小,
  閉じる姿勢は 予想の GRASP_CLOSED のコマの関節 5 つ (閉じる間に腕が着いた所) で 爪を GRASP_OPEN の予想の値から 0 へ.
  指令どおりの道では GRASP_OPEN のコマ (= 依頼 399 と同じ数になる)

  SO101_VAR_ROLL_RANGE=-67,58 /opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python so101/check_401/sweep_401.py plan|places
"""
import copy
import json
import sys
import time
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
for p in (SO101 / "ideal_var", SO101 / "check_399"):
    sys.path.insert(0, str(p))
import rule_401 as R401  # noqa: E402

OUT = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log12/401")
SHIFTS = [4.0, 8.0, 12.0, 16.0]
YAWS = [-8.0, 8.0]
INWARD_PX, INWARD_MAX = 8.0, 12
_W = {}


def W():
    if "w" not in _W:
        _W["w"] = R401.world()
    return _W["w"]


def r2(x):
    return None if x is None or not np.isfinite(x) else round(float(x), 2)


def perts(w, b, a):
    import recover_377 as RC
    u, r = RC.block_frame(b)
    out = [("なし", 0.0, np.zeros(2), 0.0)]
    for nm, vec in (("右", r), ("左", -r), ("奥", u), ("手前", -u)):
        out += [(nm, s, vec * s, 0.0) for s in SHIFTS]
    out += [("向き", dy, np.zeros(2), dy) for dy in YAWS]
    out += [("固定側へ", 8.0, a * 8.0, 0.0)]
    return out


def shape(w, path, fr, bb, yy, close_k=None):
    """形の確かめ (path = 指令 か 予想). close_k: 予想のつかむ所のコマ (None = 指令. GRASP_OPEN)"""
    sc, geo, J = w.sc, w.geo, w.J
    a0, go, gc = fr["ABOVE_BLOCK"], fr["GRASP_OPEN"], fr["GRASP_CLOSED"]
    kf = go if close_k is None else max(close_k, go)
    sc.block(bb, yy)
    fmin = mmin = np.inf
    for f in range(a0, kf + 1):
        sc.pose(path[f])
        fmin = min(fmin, geo.dist(J.fixed, geo.blk))
        if f <= go:
            mmin = min(mmin, geo.dist(J.moving, geo.blk))
    q = np.r_[path[go if close_k is None else gc][:5], path[go][5]]
    g_hit = None
    for g in np.linspace(q[5], 0.0, 41):
        sc.pose(np.r_[q[:5], g])
        if geo.dist(J.moving, geo.blk) <= 0.0:
            g_hit = float(g)
            break
    sc.block([1000, 1000], 0)
    fg = w.gaps(q, bb, yy)["fixed"]
    ok = bool(fmin > 0 and mmin > 0 and g_hit is not None and g_hit > 1.0 and fg is not None)
    return {"ok": ok, "fixed_min": r2(fmin), "moving_min": r2(mmin), "moving_hit_grip": None if g_hit is None else round(g_hit, 1),
            "fixed_gap": fg}


def now_case(w, res, e):
    """今の決まり (rule_351 の道そのまま) の 指令と予想のすき間"""
    v = w.variant(res, e)              # 開き 31.6・寄せない・下げない (= rule_351 の道)
    m = R401.measure(w, v, e)
    return dict(v, status="rule_351", dz_mm=0.0, cmd=m["cmd"], pred=m["pred"], pred_path=m["Qp"])


def one_site(w, res, e, robust=True):
    b, yaw = w.bxy(e), e["yaw"]
    out = {"block_xy": np.round(b, 1).tolist(), "yaw": yaw, "cases": {}}
    a, _ = w.jaw_dir(res["path"][res["frames"]["GRASP_OPEN"]])
    for name, fn in (("now", now_case), ("rule401", R401.apply)):
        v = fn(w, res, e)
        c = {k: v.get(k) for k in ("ok", "why", "status", "dz_mm", "cmd", "pred")}
        c["info"] = v.get("info")
        c["steps"] = v.get("steps")
        if v.get("path") is None:
            out["cases"][name] = c
            continue
        path, Qp, fr = np.asarray(v["path"]), np.asarray(v["pred_path"]), v["frames"]
        c["frames"] = {k: int(x) for k, x in fr.items()}
        if robust:
            rows = []
            for nm, s, dxy, dy in perts(w, b, a):
                bb, yy = b + dxy, yaw + dy
                rows.append({"dir": nm, "mm": s, "cmd": shape(w, path, fr, bb, yy),
                             "pred": shape(w, Qp, fr, bb, yy, v["pred"]["close_frame"])})
            c["robust"] = rows
        out["cases"][name] = c
    return out


def plan_one(i):
    w = W()
    e = w.plan["episodes"][i]
    res = w.rule(e)
    if not res.get("ok"):
        return {"index": i, "rule_ok": False, "why": res.get("why")}
    return {"index": i, "rule_ok": True, **one_site(w, res, e)}


# ---- 実機の 5 か所 -----------------------------------------------------------------------------

def place_median(place):
    d = json.loads((SO101 / "check_399" / "closes_399.json").read_text())
    t = [x for x in d["trials"] if x["model"] == "so101f" and x["place"] == place]
    xy = np.median([x["block_xy0"] for x in t], 0)
    yaw = float(np.median([x["yaw"] for x in t if x["yaw"] is not None]))
    return xy, yaw, len(t)


def ep_at(w, src, xy, yaw):
    """割り振りの本 src の 面のずらし・爪の傾きのまま ブロックを xy・yaw (90° ごとに同じ) に置き換えた本と道. 作れなければ (None, 理由)"""
    import sim_330 as S
    import yaw_lib_343 as Y
    e = copy.deepcopy(src)
    e["pixel"] = [float(v) for v in S.project_arm([[xy[0], xy[1], Y.BLOCK_MM / 2]], w.w.cam).reshape(-1)[:2]]
    why = ""
    for k in (0, 1, -1, 2):
        e["yaw"] = yaw + 90.0 * k
        r = w.rule(e)
        if r.get("ok"):
            return e, r
        why = r.get("why", "")
    return None, why


def place_search(w, xy, yaw):
    """実機の置き方 (xy・yaw) で道を作る. 1) いちばん近い割り振りの本の面・傾き (依頼 399 と同じ) 2) 近い順に全部の本の面・傾き
    3) 校正の点の真ん中へ 8 画素ずつ寄せて 1)・2) (rule_351 の作れない置き場所の寄せ方と同じ). → (本, 道, 探した記録)"""
    import sim_330 as S
    import yaw_lib_343 as Y
    eps = w.plan["episodes"]
    order = sorted(range(len(eps)), key=lambda i: float(np.linalg.norm(w.bxy(eps[i]) - xy)))
    uv0 = S.project_arm([[xy[0], xy[1], Y.BLOCK_MM / 2]], w.w.cam).reshape(-1)[:2]
    import plan_377 as P377
    import var_lib_314 as V
    center = V.GraspMap(V.load_calib(P377.CALIB)[1]).P.mean(0)          # rule_351.make_plan と同じ 校正の点の真ん中
    log = []
    for k in range(INWARD_MAX + 1):
        if k:
            d = center - uv0
            uv = uv0 + d / np.linalg.norm(d) * INWARD_PX * k
            xyk = np.asarray(Y.pixel_to_desk_mm(w.w.cam, uv), np.float64)
        else:
            xyk = np.asarray(xy, np.float64)
        for j, i in enumerate(order if k == 0 else order[:10]):
            e, r = ep_at(w, eps[i], xyk, yaw)
            if e is not None:
                log.append({"inward_px": INWARD_PX * k, "from_plan_index": i, "nearest_rank": j, "ok": True})
                return e, r, {"inward_px": INWARD_PX * k, "from_plan_index": i, "nearest_rank": j,
                              "moved_mm": r2(float(np.linalg.norm(xyk - xy))), "block_xy_used": np.round(xyk, 1).tolist(),
                              "tried": len(log) + j, "first_why": first_why(w, eps[order[0]], xy, yaw)}
        log.append({"inward_px": INWARD_PX * k, "ok": False})
    return None, None, {"tried": log, "first_why": first_why(w, eps[order[0]], xy, yaw)}


def first_why(w, src, xy, yaw):
    _, why = ep_at(w, src, xy, yaw)
    return why if isinstance(why, str) else ""


def place_one(place):
    w = W()
    xy, yaw, n = place_median(place)
    e, res, found = place_search(w, xy, yaw)
    out = {"place": place, "trials": n, "block_xy_median": np.round(xy, 1).tolist(), "yaw_median": round(yaw, 1), "search": found}
    if e is None:
        out["rule_ok"] = False
        return out
    out.update({"rule_ok": True, "from_plan_index": found["from_plan_index"], "pixel": e["pixel"], "yaw_used": e["yaw"],
                **one_site(w, res, e)})
    return out


def run(fn, idx, name, workers=8):
    t = time.time()
    with ProcessPoolExecutor(workers) as ex:
        rows = list(ex.map(fn, idx))
    OUT.mkdir(parents=True, exist_ok=True)
    doc = {"made_by": f"so101/check_401/sweep_401.py {name} (依頼 401 の 2)", "rule": R401.RULE, "shifts_mm": SHIFTS, "yaws": YAWS,
           "seconds": round(time.time() - t, 1), "rows": rows}
    p = OUT / f"sweep_401_{name}.json"
    p.write_text(json.dumps(doc, ensure_ascii=False, indent=1) + "\n")
    print("[WROTE]", p, doc["seconds"], "s", flush=True)


def main():
    what = sys.argv[1]
    if what == "plan":
        idx = list(range(50)) if len(sys.argv) < 3 else [int(x) for x in sys.argv[2].split(",")]
        run(plan_one, idx, "plan")
    elif what == "places":
        run(place_one, [1, 2, 3, 4, 5], "places", workers=5)
    else:
        raise SystemExit("plan | places")


if __name__ == "__main__":
    main()
