"""SO-101 の机側カメラの, 机 (平らに置いた A3 のボード) に対する位置と向きを出す (依頼 324).

レンズは依頼 323 の so101/check_323/desk/camera_desk.json (内部パラメータ・歪み5つ) を使う.
机側だけ camera_lock_259.apply_and_verify(keys=("desk",)) で固定の値を当てる (値は変えない. 手首は当てない = -r を使わない).
640×480・30fps・MJPG で開き, 30コマ捨ててから N 枚撮る. 窓は出さない. アームには触らない.

ボードの座標 (mm):
  原点 A = 内側の角の1つ. 外側の対角のマスが黒く, 画像でいちばん下 (= アームの側) にある角を選ぶ.
  x・y = A からボードの縁に沿って内へ. Z=0 がボードの面. z = x × y (右手系) が上 (カメラの側) を向くように,
  長い辺 (内側の角 9 個の向き) と短い辺 (6 個の向き) のどちらを x にするかを1枚目で決める (逆なら入れ替える).
  B = A に一番近い外側の黒いマスの角 (チェッカー模様の一番外の角) = (-38, -38, 0).

使い方 (conda の lerobot 環境で):
    python so101/check_324/check_324_pose.py [--frames 10]
    → so101/check_324/desk_pose.json, desk_pose.png, frames/
"""

import argparse
import json
import math
import sys
import time
from datetime import datetime
from pathlib import Path

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
sys.path.insert(0, str(SO101))
from camera_lock_259 import apply_and_verify, open_cap, opencv_index  # noqa: E402

PATTERN = (9, 6)  # 内側の角 (横, 縦)
SQUARE_MM = 38.0
DISCARD = 30
INTERVAL_S = 0.3
CALIB = SO101 / "check_323/desk/camera_desk.json"


def find_corners(gray):
    ok, c = cv2.findChessboardCornersSB(gray, PATTERN, flags=cv2.CALIB_CB_EXHAUSTIVE | cv2.CALIB_CB_ACCURACY)
    if ok:
        return c.reshape(-1, 2), "findChessboardCornersSB"
    ok, c = cv2.findChessboardCorners(gray, PATTERN, flags=cv2.CALIB_CB_ADAPTIVE_THRESH | cv2.CALIB_CB_NORMALIZE_IMAGE)
    if ok:
        c = cv2.cornerSubPix(gray, c, (5, 5), (-1, -1),
                             (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.01))
        return c.reshape(-1, 2), "findChessboardCorners+cornerSubPix"
    return None, None


def capture(n):
    applied = apply_and_verify(keys=("desk",))
    print("机側の固定の値:", json.dumps(applied, ensure_ascii=False))
    cap = open_cap(opencv_index("desk"))  # 640×480・30fps・MJPG
    frames = []
    try:
        time.sleep(0.5)
        for _ in range(DISCARD):
            cap.read()
        for _ in range(n):
            ok, f = cap.read()
            if ok and f is not None:
                frames.append(f)
            time.sleep(INTERVAL_S)
        info = {"width": int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), "height": int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
                "fps": cap.get(cv2.CAP_PROP_FPS)}
    finally:
        cap.release()
    return frames, info, applied


def grid_for_origin(pts, r0, c0, swap=False):
    """原点 (r0, c0) から内へ列・行が増える並びに直した角の画素と物体の座標を返す.
    swap=False: x = 列 (長い辺), y = 行 (短い辺). swap=True: x = 行, y = 列."""
    g = pts.reshape(PATTERN[1], PATTERN[0], 2)
    if r0:
        g = g[::-1]
    if c0:
        g = g[:, ::-1]
    obj = np.zeros((PATTERN[1], PATTERN[0], 3), np.float32)
    obj[..., 0] = np.arange(PATTERN[0])[None, :] * SQUARE_MM
    obj[..., 1] = np.arange(PATTERN[1])[:, None] * SQUARE_MM
    if swap:
        obj = obj[..., [1, 0, 2]]
    return np.ascontiguousarray(g.reshape(-1, 2)), obj.reshape(-1, 3)


def patch_mean(gray, p, r=4):
    x, y = int(round(p[0])), int(round(p[1]))
    h, w = gray.shape
    if not (r <= x < w - r and r <= y < h - r):
        return None
    return float(gray[y - r:y + r + 1, x - r:x + r + 1].mean())


def choose_origin(gray, pts):
    """外側の対角のマスが黒い角の中で, 画像でいちばん下の角を原点にする."""
    cands = []
    for r0 in (0, PATTERN[1] - 1):
        for c0 in (0, PATTERN[0] - 1):
            img, obj = grid_for_origin(pts, r0, c0)
            H, _ = cv2.findHomography(obj[:, :2], img)
            q = cv2.perspectiveTransform(np.float32([[[-19, -19]], [[19, -19]]]), H).reshape(-1, 2)
            out_diag, out_side = patch_mean(gray, q[0]), patch_mean(gray, q[1])
            black = out_diag is not None and out_side is not None and out_diag < out_side
            cands.append({"r0": r0, "c0": c0, "px": img[0].tolist(), "black": black,
                          "gray_diag": out_diag, "gray_side": out_side})
    blacks = [c for c in cands if c["black"]]
    if not blacks:
        raise RuntimeError(f"外側の対角のマスが黒い角が見つからない {cands}")
    return max(blacks, key=lambda c: c["px"][1]), cands


def origin_nearest(pts, ref_px):
    """1枚目で決めた原点の画素に一番近い角 (4隅のうち) を, 2枚目以降の原点にする."""
    best = None
    for r0 in (0, PATTERN[1] - 1):
        for c0 in (0, PATTERN[0] - 1):
            img, _ = grid_for_origin(pts, r0, c0)
            d = float(np.linalg.norm(img[0] - ref_px))
            if best is None or d < best[0]:
                best = (d, r0, c0)
    return best[1], best[2]


def euler_zyx(R):
    """R = Rz(yaw) Ry(pitch) Rx(roll) の yaw, pitch, roll (度)."""
    pitch = math.degrees(math.asin(max(-1.0, min(1.0, -R[2, 0]))))
    roll = math.degrees(math.atan2(R[2, 1], R[2, 2]))
    yaw = math.degrees(math.atan2(R[1, 0], R[0, 0]))
    return yaw, pitch, roll


def solve(img, obj, K, D):
    ok, rvec, tvec = cv2.solvePnP(obj, img, K, D, flags=cv2.SOLVEPNP_ITERATIVE)
    if not ok:
        raise RuntimeError("solvePnP が解けない")
    rvec, tvec = cv2.solvePnPRefineLM(obj, img, K, D, rvec, tvec)
    proj, _ = cv2.projectPoints(obj, rvec, tvec, K, D)
    err = np.linalg.norm(proj.reshape(-1, 2) - img, axis=1)
    R, _ = cv2.Rodrigues(rvec)
    Rbc = R.T  # カメラの軸をボードの座標で表したもの (列 = カメラの x 右・y 下・z 光軸)
    C = (-R.T @ tvec).ravel()  # ボードの座標でのカメラの位置
    axis = Rbc[:, 2]
    down = np.array([0.0, 0.0, -1.0 if C[2] > 0 else 1.0])  # カメラの側から机へ向かう向き
    tilt = math.degrees(math.acos(max(-1.0, min(1.0, float(axis @ down)))))
    heading = math.degrees(math.atan2(axis[1], axis[0]))  # 光軸を机に落とした向き (+x から +y へ)
    right = Rbc[:, 0]
    img_right = math.degrees(math.atan2(right[1], right[0]))  # 画像の右向きを机に落とした向き
    # 光軸と机の交わる点
    s = -C[2] / axis[2] if abs(axis[2]) > 1e-9 else float("nan")
    hit = C + s * axis
    yaw, pitch, roll = euler_zyx(Rbc)
    return {
        "rvec": rvec.ravel().tolist(), "tvec_mm": tvec.ravel().tolist(),
        "rodrigues_cam_in_board": cv2.Rodrigues(Rbc)[0].ravel().tolist(),
        "rodrigues_cam_in_board_angle_deg": math.degrees(float(np.linalg.norm(cv2.Rodrigues(Rbc)[0]))),
        "R_board_to_cam": R.tolist(), "R_cam_in_board": Rbc.tolist(),
        "cam_pos_mm": C.tolist(), "height_mm": abs(float(C[2])), "cam_on_plus_z": bool(C[2] > 0),
        "tilt_from_down_deg": tilt, "axis_heading_deg": heading, "image_right_heading_deg": img_right,
        "axis_hits_board_mm": hit[:2].tolist(),
        "euler_zyx_cam_in_board_deg": {"yaw_z": yaw, "pitch_y": pitch, "roll_x": roll},
        "reproj_rms_px": float(np.sqrt((err ** 2).mean())), "reproj_max_px": float(err.max()),
    }


def stats(vals):
    a = np.array(vals, float)
    return {"mean": round(float(a.mean()), 3), "std": round(float(a.std(ddof=1)) if len(a) > 1 else 0.0, 3),
            "min": round(float(a.min()), 3), "max": round(float(a.max()), 3)}


def put(img, text, p, color, scale=0.7):
    p = (int(p[0]), int(p[1]))
    cv2.putText(img, text, p, cv2.FONT_HERSHEY_SIMPLEX, scale, (255, 255, 255), 4, cv2.LINE_AA)
    cv2.putText(img, text, p, cv2.FONT_HERSHEY_SIMPLEX, scale, color, 2, cv2.LINE_AA)


def draw(frame, img, rvec, tvec, K, D, res):
    vis = frame.copy()
    for p in img:
        cv2.circle(vis, (int(round(p[0])), int(round(p[1]))), 2, (0, 200, 0), -1)
    pts3 = np.float32([[0, 0, 0], [3 * SQUARE_MM, 0, 0], [0, 3 * SQUARE_MM, 0], [-SQUARE_MM, -SQUARE_MM, 0]])
    q, _ = cv2.projectPoints(pts3, rvec, tvec, K, D)
    A, X, Y, B = [tuple(int(round(v)) for v in p) for p in q.reshape(-1, 2)]
    cv2.arrowedLine(vis, A, X, (0, 0, 255), 3, tipLength=0.12)
    cv2.arrowedLine(vis, A, Y, (0, 160, 0), 3, tipLength=0.12)
    put(vis, "x", (X[0] + 6, X[1] + 6), (0, 0, 255), 0.9)
    put(vis, "y", (Y[0] + 6, Y[1] - 6), (0, 160, 0), 0.9)
    cv2.circle(vis, A, 11, (0, 0, 255), 3)
    put(vis, "A", (A[0] + 10, A[1] - 12), (0, 0, 255), 0.9)
    cv2.circle(vis, B, 9, (255, 0, 0), 3)
    put(vis, "B", (B[0] - 30, B[1] + 26), (255, 0, 0), 0.9)
    put(vis, f"h={res['height_mm']['mean']:.1f}mm tilt={res['tilt_from_down_deg']['mean']:.1f}deg "
             f"rms={res['reproj_rms_px']['mean']:.2f}px", (8, 22), (40, 40, 40), 0.55)
    put(vis, "B -> A: x +38mm, y +38mm", (8, 44), (40, 40, 40), 0.55)
    return vis, {"A_px": list(A), "B_px": list(B)}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--frames", type=int, default=10)
    ap.add_argument("--from-frames", nargs="+", help="撮らずに保存した画像から計算し直す (カメラは開かない)")
    args = ap.parse_args()

    cal = json.loads(CALIB.read_text())
    K = np.array(cal["camera_matrix"], float)
    D = np.array(cal["dist_coeffs"], float)

    if args.from_frames:
        paths = sorted(Path(p) for p in args.from_frames)
        frames, names = [cv2.imread(str(p)) for p in paths], [p.name for p in paths]
        info, applied = {"from_frames": True}, None
    else:
        frames, info, applied = capture(args.frames)
        (HERE / "frames").mkdir(exist_ok=True)
        stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        names = [f"desk_{stamp}_{i:02d}.png" for i in range(len(frames))]
        for name, f in zip(names, frames):
            cv2.imwrite(str(HERE / "frames" / name), f)
    per, used, origin_info, ref_px = [], [], None, None
    for name, f in zip(names, frames):
        gray = cv2.cvtColor(f, cv2.COLOR_BGR2GRAY)
        pts, method = find_corners(gray)
        if pts is None or len(pts) != PATTERN[0] * PATTERN[1]:
            per.append({"file": name, "ok": False, "why": "角が54点そろわない"})
            continue
        if ref_px is None:
            chosen, cands = choose_origin(gray, pts)
            r0, c0 = chosen["r0"], chosen["c0"]
            ref_px = np.array(chosen["px"])
            img, obj = grid_for_origin(pts, r0, c0)
            swap = not solve(img, obj, K, D)["cam_on_plus_z"]  # z が机の中を向くなら x と y を入れ替える
            origin_info = {"r0_c0_in_detection": [r0, c0], "x_along": "短い辺 (6)" if swap else "長い辺 (9)",
                           "y_along": "長い辺 (9)" if swap else "短い辺 (6)", "candidates": cands}
        else:
            r0, c0 = origin_nearest(pts, ref_px)
        img, obj = grid_for_origin(pts, r0, c0, swap)
        r = solve(img, obj, K, D)
        r.update({"file": name, "ok": True, "method": method, "A_px": img[0].tolist()})
        per.append(r)
        used.append((f, img, obj, r))

    if not used:
        out = {"time": datetime.now().isoformat(timespec="seconds"), "ok": False, "per_frame": per, "cap": info}
        (HERE / "desk_pose.json").write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n")
        print("角が54点そろった枚数が 0")
        return 2

    good = [u[3] for u in used]
    summ = {k: stats([g[k] for g in good]) for k in
            ("height_mm", "tilt_from_down_deg", "axis_heading_deg", "image_right_heading_deg",
             "reproj_rms_px", "reproj_max_px", "rodrigues_cam_in_board_angle_deg")}
    for j, ax in enumerate("xyz"):
        summ[f"cam_pos_{ax}_mm"] = stats([g["cam_pos_mm"][j] for g in good])
    for k in ("yaw_z", "pitch_y", "roll_x"):
        summ[f"euler_{k}_deg"] = stats([g["euler_zyx_cam_in_board_deg"][k] for g in good])
    for j, ax in enumerate("xy"):
        summ[f"axis_hits_board_{ax}_mm"] = stats([g["axis_hits_board_mm"][j] for g in good])

    # 平均の姿勢: 全部の枚の角の点をまとめて解き直す (位置・向きの代表値)
    img_all = np.concatenate([u[1] for u in used])
    obj_all = np.concatenate([u[2] for u in used])
    mean_pose = solve(img_all, obj_all, K, D)

    f0, img0, obj0, _ = used[0]
    vis, ab = draw(f0, img0, np.array(mean_pose["rvec"]), np.array(mean_pose["tvec_mm"]), K, D, summ)
    cv2.imwrite(str(HERE / "desk_pose.png"), vis)

    out = {
        "time": datetime.now().isoformat(timespec="seconds"),
        "made_by": "so101/check_324/check_324_pose.py (依頼 324)",
        "ok": True,
        "calib_file": str(CALIB.relative_to(SO101.parent)), "calib_rms_px": cal.get("rms_px"),
        "lock_applied": applied, "cap": info,
        "board": {"inner_corners": list(PATTERN), "square_mm": SQUARE_MM,
                  "axes": "原点 A = 内側の角 (外側の対角のマスが黒く, 画像でいちばん下の角). x・y = A から縁に沿って内へ, "
                          "z = x × y が上 (カメラの側) を向くように x・y を選ぶ (origin.x_along). ボードの面が Z=0",
                  "B_mm": [-SQUARE_MM, -SQUARE_MM, 0.0],
                  "B_to_A_mm": {"x": SQUARE_MM, "y": SQUARE_MM}},
        "origin": origin_info, "image_points": ab,
        "angles_note": {
            "tilt_from_down_deg": "光軸と真下 (カメラから机へ垂直) のなす角",
            "axis_heading_deg": "光軸を机に落とした向き. ボードの +x から +y へ回る角",
            "image_right_heading_deg": "画像の右向きを机に落とした向き. ボードの +x から +y へ回る角",
            "euler_zyx_cam_in_board_deg": "R_cam_in_board = Rz(yaw) Ry(pitch) Rx(roll). カメラの軸は OpenCV (x 右・y 下・z 前)",
            "rodrigues_cam_in_board": "カメラの向きをボードの座標で表したロドリゲス (rvec の逆)",
            "rvec": "solvePnP の rvec (ボードの座標 → カメラの座標)",
        },
        "n_frames": len(frames), "n_used": len(used),
        "summary": summ,
        "pose_all_frames_together": mean_pose,
        "per_frame": per,
    }
    (HERE / "desk_pose.json").write_text(json.dumps(out, ensure_ascii=False, indent=2) + "\n")
    print(json.dumps({"summary": summ, "image_points": ab, "origin": origin_info,
                      "pose_all": {k: mean_pose[k] for k in ("cam_pos_mm", "height_mm", "tilt_from_down_deg",
                                                             "axis_heading_deg", "image_right_heading_deg",
                                                             "rodrigues_cam_in_board", "euler_zyx_cam_in_board_deg",
                                                             "axis_hits_board_mm", "reproj_rms_px")}},
                     ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    sys.exit(main())
