"""依頼 343 の確かめ: 50 本 (向き入り) の下見・つかむ所の絵・案内の窓の見本 (yaw_check_343.py preview / window から呼ぶ).

校正の点: 今の台座で録り直したときの見込みの 13 点 (box_fit_341.predict_calib) + range で足した E9〜 (仮の正解).
割り振り: plan_315.make_plan (seed 315. 向きは plan_yaws). 3 つの場合で道を作る.
  strict: 今の安全範囲のまま 決めた向き (calib_points_315 --yaw-mode strict と同じ. 入らない本を数える)
  fit:    今の安全範囲に入る大きさまで縮めた向き (--yaw-mode fit. 案B)
  wide:   手首の回転の範囲を広げた (SO101_VAR_ROLL_RANGE. yaw_check_343.WIDE_ROLL. 案A) 決めた向きそのまま
"""
import json
import math
import os
import sys
from pathlib import Path

import numpy as np

import yaw_check_343 as C  # noqa: E402
import yaw_check2_343 as C2  # noqa: E402

BF, PL, V, Y = C.BF, C.PL, C.V, C.Y
OUT = C.OUT
REPO = C.REPO
FIG_PLACES = ["place1", "place3", "place5", "E7"]      # 絵に描く所 (+ 足した点の最初)
FIG_YAWS = [-30.0, 0.0, 30.0]


def calib_points(chain):
    """→ (見込みの点 (13 + E9〜), 仮の点 (--dry-fake と同じ. 13 + E9〜)) と, 勧める点の JSON (E9〜 の仮の値を 仮の点の正解で書き直す)"""
    import make_var_314 as MV
    rng = json.loads((OUT / "range_343.json").read_text())
    pred = C.predicted_points()
    fake = BF.fake_calib()
    t_fake = MV.Truth(fake, chain)
    t_pred = MV.Truth(pred, chain)
    add_pred, add_fake = [], []
    for p in rng["new_points"]:
        uv = np.array([p["u"], p["v"]])
        for T, lst in ((t_pred, add_pred), (t_fake, add_fake)):
            t = T(uv)
            if t is None:
                raise SystemExit(f"[ERROR] {p['name']} が仮の正解で解けない")
            lst.append({"name": p["name"], "kind": "extra", "u": p["u"], "v": p["v"],
                        "above": np.r_[t[0], V.GRIP["ABOVE_BLOCK"]].round(3).tolist(),
                        "grasp": np.r_[t[1], V.GRIP["GRASP_OPEN"]].round(3).tolist()})
    rec = json.loads((OUT / "calib_points_343.json").read_text())
    by = {p["name"]: p for p in add_fake}
    for p in rec["points"]:
        if p["name"] in by:
            p["above"], p["grasp"] = by[p["name"]]["above"], by[p["name"]]["grasp"]
    rec["fake_note"] = ("above・grasp は --dry-fake で録ったことにする値 (本番では使わない). 場所1〜5 は依頼 302 の道, E1〜E8 は依頼 314 の仮の正解, "
                        "E9〜 は同じ仮の点 13 から作った仮の正解 (依頼 343)")
    (OUT / "calib_points_343.json").write_text(json.dumps(rec, ensure_ascii=False, indent=1) + "\n")
    return pred + add_pred, fake + add_fake


def plan_for(gmap, pts, chain, A):
    places = [p for p in pts if p["kind"] == "place"]
    plan = PL.make_plan(gmap, places, A, seed=315)
    return plan, places


def build_all(gmap, plan, chain, A, lo, hi, lo_w, hi_w):
    """3 つの場合の道. → {scenario: [(e, yaw, res)]}"""
    import calib_points_315 as CP
    out = {"strict": [], "fit": [], "wide": []}
    c = gmap.P.mean(0)
    for e in plan["episodes"]:
        uv = np.array(e["pixel"], np.float64)
        det = tuple(e["detour"]) if e["detour"] else None
        for _ in range(60):
            r0 = V.make_path(gmap, uv, chain, lo, hi, offset=e["offset"], detour=det, A=A)
            if r0["ok"]:
                break
            uv = uv + 4.0 * (c - uv) / np.linalg.norm(c - uv)
        e["pixel"] = uv.round(1).tolist()
        y = float(e["yaw"])
        m = CP.YAW_FIT_MARGIN
        mk = lambda yy, l, h, mm=0.0: V.make_path(gmap, uv, chain, l, h, offset=e["offset"], detour=det, A=A,  # noqa: E731
                                                  yaw=yy + np.sign(yy) * mm)
        rs = mk(y, lo, hi, m)
        out["strict"].append((e, y, mk(y, lo, hi) if rs["ok"] else rs))
        yf = y
        if not rs["ok"]:
            sgn, mag = np.sign(y), abs(y)
            cands = [sgn * k for k in np.arange(mag - 1, PL.YAW_MIN - 1e-9, -1.0)] + [-sgn * k for k in np.arange(mag, PL.YAW_MIN - 1e-9, -1.0)]
            yf = next((float(k) for k in cands if mk(k, lo, hi, m)["ok"]), 0.0)
        out["fit"].append((e, yf, mk(yf, lo, hi)))
        out["wide"].append((e, y, mk(y, lo_w, hi_w)))
    return out


def ep_metrics(sc, geo, chain, e, yaw, res, cam):
    info = res["info"]
    xy = Y.pixel_to_desk_mm(cam, e["pixel"])
    cl = C2.path_clearance(geo, res, xy, yaw, step=2)
    q_g = np.array(info["grasp"])
    q_g0 = q_g.copy()
    q_g0[4] -= info["roll_add_grasp_deg"]
    j1, j0 = sc.jaw_yaw(q_g), sc.jaw_yaw(q_g0)
    rel = ((j1 - j0 - yaw) + 90) % 180 - 90
    width = lambda err: Y.BLOCK_MM * (abs(math.cos(math.radians(err))) + abs(math.sin(math.radians(err))))  # noqa: E731
    wv = C2.wrist_view(sc, res["keyframes"][1]["pose"], xy, yaw)
    return {"index": e["index"], "pixel": e["pixel"], "yaw": yaw, "yaw_rule": e["yaw"], "detour": bool(e["detour"]),
            "from_home": not any(e["offset"]), "frames": len(res["path"]), **cl,
            "step_max_joint_deg": info["step_max_joint_deg"], "step_max_gripper": info["step_max_gripper"],
            "roll_min": info["roll_min_deg"], "roll_max": info["roll_max_deg"], "roll_add": info["roll_add_grasp_deg"],
            "jaw_vs_block_after_add_deg": round(abs(rel), 3),
            "block_width_along_jaw_mm": {"with_add": round(width(rel), 1), "without_add": round(width(yaw), 1)},
            "wrist_view_px": round(wv, 1), "carry_z_min_mm": info["carry_z_min_mm"], "safe_margin_min": info["safe_margin_min"]}


def summarize(rows):
    s = {"n": len(rows)}
    for k, f in (("table", min), ("box", min), ("block_pad10", min), ("base", min), ("grasp_table", min), ("wrist_view_px", min),
                 ("step_max_joint_deg", max), ("step_max_gripper", max), ("roll_min", min), ("roll_max", max),
                 ("jaw_vs_block_after_add_deg", max), ("carry_z_min_mm", min)):
        vals = [r[k] for r in rows]
        i = int((np.argmin if f is min else np.argmax)(vals))
        s[k] = {"value": vals[i], "index": rows[i]["index"]}
    y = np.array([r["yaw"] for r in rows])
    s["yaw"] = {"zero": int((y == 0).sum()), "plus": int((y > 0).sum()), "minus": int((y < 0).sum()),
                "min": float(y.min()), "max": float(y.max()), "abs_mean_nonzero": round(float(np.abs(y[y != 0]).mean()), 1)}
    return s


def preview(argv):
    import cv2
    import run_so101_policy as R
    chain = V.load_urdf_chain(V.URDF)
    lo, hi, _ = R.load_safe_range(R.DEFAULT_RAW)
    lo_w, hi_w = lo.copy(), hi.copy()
    lo_w[4], hi_w[4] = C.WIDE_ROLL
    pred, fake = calib_points(chain)
    gmap = V.GraspMap(pred)
    A, _ = V.pixel_mm_affine(pred, chain)
    plan, places = plan_for(gmap, pred, chain, A)
    built = build_all(gmap, plan, chain, A, lo, hi, lo_w, hi_w)
    sc = C.Scene(render=True)
    geo = C2.Geo(sc)
    cam = Y.desk_cam()
    rest = C2.arm_rest_mask(sc)
    doc = {"made_by": "so101/ideal_var/yaw_check_343.py preview (依頼 343 の 5)",
           "calib": "今の台座で録り直したときの見込み (13 点) + E9〜 (仮の正解)", "n_points": len(pred),
           "safe_range_roll": [round(float(lo[4]), 2), round(float(hi[4]), 2)], "wide_roll": list(C.WIDE_ROLL),
           "note": "table = 下ろす・閉じる・持ち上げるの間を除いた 手首・爪・カメラから机. base = ブロックのまわりの間の 台座・肩まで. "
                   "block_pad10 = ブロックの上に来るまでの ブロック (+10mm) まで. jaw_vs_block_after_add = 手首の回転を足したあと "
                   "MuJoCo の爪の向きの変化 − ブロックの向き. block_width_along_jaw = 爪が閉じる向きに見たブロックの幅 (21.7 = そろっている)",
           "scenarios": {}}
    for scen, items in built.items():
        bad = [(e["index"], y, r["why"]) for e, y, r in items if not r["ok"]]
        rows = [ep_metrics(sc, geo, chain, e, y, r, cam) for e, y, r in items if r["ok"]]
        occ = []
        for e, y, r in items:
            hm, _ = C2.block_hull_mask(cam, Y.pixel_to_desk_mm(cam, e["pixel"]), y)
            occ.append(float((hm & rest).sum()) / max(1, hm.sum()))
        summ = summarize(rows) if rows else {}
        summ["desk_occluded_max"] = round(max(occ), 3)
        doc["scenarios"][scen] = {"made": len(rows), "refused": bad, "summary": summ, "episodes": rows}
        print(f"[PREVIEW] {scen}: 道ができた {len(rows)}/50  作れない {len(bad)}  " + json.dumps(summ, ensure_ascii=False)[:900])
    C.dump("preview_343.json", doc)
    # 窓・--dry-fake 用の 校正の点と割り振り (見込み. 向きは fit)
    for e, (_, yf, _) in zip(plan["episodes"], built["fit"]):
        e["yaw_fit"] = yf
    (OUT / "calib_pred_343.json").write_text(json.dumps({"request": 343, "fake": True, "points": pred}, ensure_ascii=False, indent=1) + "\n")
    (OUT / "plan_pred_343.json").write_text(json.dumps(plan, ensure_ascii=False, indent=1) + "\n")
    figures(sc, chain, gmap, pred, built["wide"], cam)
    plan_figure(pred, plan, cam)
    sc.rp.cr.close()
    return 0


# ---- 絵 --------------------------------------------------------------------------------------

def top_view(sc, rend, center_mm, size=0.16):
    import mujoco
    cam = mujoco.MjvCamera()
    cam.type = mujoco.mjtCamera.mjCAMERA_FREE
    import make_sim_demo_330 as Dm
    cam.lookat[:] = (np.asarray(center_mm) + Dm.AXIS_OFF) / 1000
    cam.distance, cam.elevation, cam.azimuth = size, -90.0, 180.0
    opt = mujoco.MjvOption()
    opt.geomgroup[4] = 1
    rend.update_scene(sc.d, camera=cam, scene_option=opt)
    return rend.render()[:, :, ::-1].copy()


def top_schematic(tip, a, yaw, size=360, k=6.0):
    """上から見た図 (机の上. 画面の上 = 前 (+x), 左 = +y). 緑 = ブロック (向き yaw), 赤 = 爪が閉じる向き, 灰 = 爪の面 (閉じる向きに直角)"""
    import cv2
    img = np.full((size, size, 3), 255, np.uint8)
    c0 = np.array([size / 2, size / 2 + 10])
    P = lambda xy: tuple(np.round(c0 + np.array([-(xy[1] - tip[1]), -(xy[0] - tip[0])]) * k).astype(int))  # noqa: E731
    h = Y.BLOCK_MM / 2
    ca, sa = math.cos(math.radians(yaw)), math.sin(math.radians(yaw))
    sq = [tip[:2] + np.array([ca * x - sa * y, sa * x + ca * y]) for x, y in ((-h, -h), (h, -h), (h, h), (-h, h))]
    cv2.fillPoly(img, [np.array([P(q) for q in sq], np.int32)], (120, 220, 120))
    cv2.polylines(img, [np.array([P(q) for q in sq], np.int32)], True, (0, 120, 0), 2, cv2.LINE_AA)
    a2 = np.asarray(a[:2], np.float64) / np.linalg.norm(a[:2])
    n2 = np.array([-a2[1], a2[0]])
    for sgn in (-1, 1):                       # 爪の面 (開いた爪の内側. ブロックの半分 + 3 mm の所)
        c = tip[:2] + sgn * a2 * (h + 3)
        cv2.line(img, P(c - n2 * 12), P(c + n2 * 12), (90, 90, 90), 4, cv2.LINE_AA)
    cv2.line(img, P(tip[:2] - a2 * 22), P(tip[:2] + a2 * 22), (0, 0, 230), 1, cv2.LINE_AA)
    cv2.arrowedLine(img, (20, size - 20), (20, size - 60), (0, 0, 0), 1, tipLength=0.25)
    cv2.putText(img, "+x (front)", (26, size - 50), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 0), 1, cv2.LINE_AA)
    return img


def label(img, text, col=(0, 0, 0)):
    import cv2
    cv2.rectangle(img, (0, 0), (img.shape[1], 22), (255, 255, 255), -1)
    cv2.putText(img, text, (4, 16), cv2.FONT_HERSHEY_SIMPLEX, 0.45, col, 1, cv2.LINE_AA)
    return img


def figures(sc, chain, gmap, pts, wide, cam):
    """場所ごとに 向き -30・0・+30 (足した) と +30 (足さない) を: 上から見た図 (つかむ所. 爪の面とブロック) と 手首の絵 (ブロックの上).
    ブロックは つかむ所の爪の先の真下に置く (爪の間に来る置き方. シムの関節の 0 のずれで位置は少し違うので, 向きを見る図)"""
    import cv2
    import mujoco
    rend = mujoco.Renderer(sc.m, 360, 360)
    names = FIG_PLACES + [p["name"] for p in pts if p["name"].startswith("E") and int(p["name"][1:]) >= 9][:2]
    lo, hi = np.full(6, -1e9), np.full(6, 1e9)
    for nm in names:
        p = next(q for q in pts if q["name"] == nm)
        uv = np.array([p["u"], p["v"]], np.float64)
        uv += 6.0 * (gmap.P.mean(0) - uv) / np.linalg.norm(gmap.P.mean(0) - uv)     # 囲みの縁の点は少し内側で描く
        tops, wrists = [], []
        g = gmap(uv)
        if g is None:
            print(f"[FIG ] {nm}: 範囲の外")
            continue
        # 校正の点で 爪をブロック (0°) の面にそろえて録った見込み: 補った姿勢の手首の回転を, 爪の向きが机の縦横にそろう
        # いちばん近い所へ回す (見込みの点は依頼 302 の道の手首の回転のままで, そろっていないため)
        base = []
        for q in g:
            q = np.asarray(q, np.float64).copy()
            d0, _ = Y.roll_for_yaw(chain, q, -Y.fold(Y.jaw_yaw(chain, q)))
            q[4] += d0
            base.append(q)
        for yaw, add in [(y, True) for y in FIG_YAWS] + [(30.0, False)]:
            ab, gr = base[0].copy(), base[1].copy()
            if add:
                ab[4] += Y.roll_for_yaw(chain, ab, yaw)[0]
                gr[4] += Y.roll_for_yaw(chain, gr, yaw)[0]
            ab, gr = np.r_[ab, V.GRIP["ABOVE_BLOCK"]], np.r_[gr, V.GRIP["GRASP_OPEN"]]
            r = {"info": {"roll_add_grasp_deg": gr[4] - base[1][4]}}
            sc.pose(gr)
            tip, a, b = sc.rp.jaw_dirs()
            sc.block(tip[:2], yaw)                   # ブロックは爪の間 (爪の先の真下) に置く
            sc.pose(gr)
            t = label(top_schematic(tip, a, yaw), f"{nm} yaw {yaw:+.0f} roll {gr[4]:+.1f} ({'add ' + format(r['info']['roll_add_grasp_deg'], '+.1f') if add else 'NO add'})",
                      (0, 0, 0) if add else (0, 0, 200))
            # 爪の閉じる向き (赤) とブロックの面 (緑) の線
            tops.append(t)
            sc.pose(ab)
            w = sc.render("wrist")
            w = cv2.resize(w, (360, 270))
            wrists.append(label(w, f"wrist at ABOVE_BLOCK yaw {yaw:+.0f} {'' if add else 'NO add'}", (0, 0, 0) if add else (0, 0, 200)))
        sc.block([1000, 1000], 0)
        img = np.vstack([np.hstack(tops), np.hstack(wrists)])
        cv2.putText(img, "top view: image up = robot -x (toward base)? see arrow", (4, 352), cv2.FONT_HERSHEY_SIMPLEX, 0.0001, (0, 0, 0), 1)
        p_ = OUT / f"grasp_view_343_{nm}.png"
        cv2.imwrite(str(p_), img)
        print("[OUT ]", p_.relative_to(REPO))
    rend.close()


def plan_figure(pts, plan, cam):
    """今の机の写真の上に: 前の範囲 (13 点. 灰) と広げた範囲 (緑), 校正の点, 50 本の位置と向き (水色の傾いた四角), 箱. 左に依頼 314 の図"""
    import cv2
    import sim_330 as S
    img = cv2.resize(cv2.imread(str(BF.DESK_PHOTO)), (640, 480))
    box = BF.load_box()
    rim = S.project_arm(np.array(S.box_corners(box["xy"], box["yaw"], box["size_xy"], box["height"], box["height"])[:4]), cam)
    cv2.polylines(img, [np.round(rim).astype(np.int32)], True, (0, 140, 255), 2, cv2.LINE_AA)
    old = [p for p in pts if p["kind"] == "place" or int(p["name"][1:]) <= 8]
    cv2.polylines(img, [V.convex_hull([[p["u"], p["v"]] for p in old]).astype(np.int32)], True, (90, 90, 90), 2, cv2.LINE_AA)
    cv2.polylines(img, [V.convex_hull([[p["u"], p["v"]] for p in pts]).astype(np.int32)], True, (0, 170, 0), 2, cv2.LINE_AA)
    for e in plan["episodes"]:
        y = e.get("yaw_fit", e["yaw"])
        sq = Y.square_px(cam, e["pixel"], e["yaw"])
        cv2.polylines(img, [np.round(sq).astype(np.int32)], True, (200, 140, 0), 1, cv2.LINE_AA)
        if y != e["yaw"]:
            cv2.polylines(img, [np.round(Y.square_px(cam, e["pixel"], y)).astype(np.int32)], True, (200, 0, 200), 1, cv2.LINE_AA)
    for p in pts:
        c = (int(p["u"]), int(p["v"]))
        col = (0, 0, 0) if p["kind"] == "place" else ((0, 0, 230) if int(p["name"][1:]) <= 8 else (200, 0, 200))
        cv2.drawMarker(img, c, col, cv2.MARKER_TILTED_CROSS, 14, 2, cv2.LINE_AA)
        cv2.putText(img, p["name"].replace("place", "P"), (c[0] + 7, c[1] + 4), cv2.FONT_HERSHEY_SIMPLEX, 0.45, col, 1, cv2.LINE_AA)
    cv2.putText(img, "343: gray = range now (13 pts)  green = new range  squares = 50 blocks with yaw  orange = box", (8, 16),
                cv2.FONT_HERSHEY_SIMPLEX, 0.42, (0, 0, 0), 1, cv2.LINE_AA)
    cv2.imwrite(str(OUT / "plan_preview_343.png"), img)
    old_png = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log12/314/plan_preview_314.png")
    o = cv2.imread(str(old_png))
    if o is not None:
        o = cv2.resize(o, (640, 480))
        cv2.putText(o, "314 (before)", (8, 470), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 200), 2, cv2.LINE_AA)
        cv2.imwrite(str(OUT / "plan_preview_314_vs_343.png"), np.hstack([o, img]))
    print("[OUT ]", (OUT / "plan_preview_343.png").relative_to(REPO), (OUT / "plan_preview_314_vs_343.png").relative_to(REPO))


# ---- 窓の見本 ---------------------------------------------------------------------------------

def window(argv):
    import cv2
    import preview_315 as P
    calib, plan = OUT / "calib_pred_343.json", OUT / "plan_pred_343.json"
    photo = cv2.imread(str(BF.DESK_PHOTO))
    eps = json.loads(plan.read_text())["episodes"]
    idx = int(argv[0]) if argv else 0
    res = []
    for tag, yaw, put in (("0", 0.0, 2.0), ("p30", 30.0, 27.5), ("m30", -30.0, -31.5), ("ng_p30", 30.0, 12.0)):
        judge = P.Judge(str(calib), str(plan), idx)
        judge.e = dict(eps[idx], yaw=yaw)
        judge.yaw_plan = yaw
        rgb = cv2.resize(photo, (640, 480))[..., ::-1].copy()
        uv = P.fake_uv("plan", judge.e)
        P.paint_cube(rgb, uv, put, judge.cam)              # 写真の上に描いた仮のブロック (置いた向き put)
        det, why_det, ok, why, yr = P.look(rgb, judge)
        img = P.draw(rgb, judge, det, why_det, ok, why, note=f"(依頼343 の見本: 置いた向き {put:+.1f}°)", yr=yr)
        p = OUT / f"window_sample_343_{tag}.png"
        cv2.imwrite(str(p), img)
        res.append({"tag": tag, "plan_yaw": yaw, "painted_yaw": put, "read": yr, "ok": ok, "why": why, "png": str(p.relative_to(REPO))})
        print(f"[WINDOW] {p.relative_to(REPO)}  置く {yaw:+.0f}° 描いた {put:+.1f}° 読んだ {None if yr is None else yr['yaw']}  進める {ok} {why}")
    C.dump("window_343.json", {"photo": str(BF.DESK_PHOTO.relative_to(REPO)), "index": idx, "samples": res})
    return 0
