"""SO-101 のカメラ (机側・手首) のレンズの画角と歪みを測る: 撮影と計算 (依頼 323).

チェッカーボード (どちらも 10×7 マス = 内側の角 9×6) を写して, cv2.calibrateCamera で
内部パラメータ (fx, fy, cx, cy) と歪み係数 5つ (k1, k2, p1, p2, k3) を出す. アームには触らない.

始めに camera_lock_259.apply_and_verify(keys=(<そのカメラだけ>,)) で固定の値を当てる (値は変えない.
もう片方のカメラには触らない). uvc-util -r は使わない: 手首の露出が自動 (8) になっていなければ,
当てる前に止める (apply_and_verify は手動になっていると中で -r を使うため).

使い方 (conda の lerobot 環境で):
    python so101/calib_camera.py --cam desk  --board a3 --out so101/check_323/desk
    python so101/calib_camera.py --cam wrist --board a4 --out so101/check_323/wrist
    python so101/calib_camera.py --cam desk  --board a3 --out so101/check_323/desk --calibrate-only --drop-worst 3

撮影中の窓:
    角が54点そろい, 止まっていて (ぼけていない), それまでのどの1枚とも位置か形が十分違えば自動で1枚保存.
    スペース = 手で1枚保存 (違いの判定はしない. 角がそろっていることだけ見る). q = 終わって計算へ.
出力 (--out の下):
    frames/{cam}_{NNN}_{時刻}.png  元の画像のまま
    frames/capture_meta.json       固定の値・カメラの名前・開いたときの大きさ (撮影のたびに書く)
    camera_{cam}.json              計算の結果 (前のものがあれば camera_{cam}.prev_{時刻}.json に写してから書く)
    undistort_check.png            左 = 元, 右 = 歪みを補正した画像
"""

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

import cv2
import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from camera_lock_259 import (AE_AUTO, AE_MODE, CAMERAS, CameraLockError, apply_and_verify,  # noqa: E402
                             find_device, get_value, load_lock, open_cap, opencv_index)

PATTERN = (9, 6)  # 内側の角 (横, 縦)
N_CORNERS = PATTERN[0] * PATTERN[1]
BOARDS = {"a3": 38.0, "a4": 25.0}  # 1マスの大きさ (mm)
TARGET = 25  # 目標の枚数
DISCARD = 30  # 開いた直後のコマを捨てる (約1秒)
# 自動で撮る条件 (オプションで変えられる)
MIN_MOVE = 0.08  # 角の重心が画面の 8% 以上動いた (横は幅, 縦は高さで割って測る)
MIN_SHAPE = 0.10  # ボードの見かけの形 (外側4つの角の並び・大きさ・傾き) の違い
MAX_STILL_PX = 1.5  # 前のコマからの角の動き (平均 px). これより大きいと動いている = ぼけるので撮らない
MIN_SHARP = 100.0  # ボードの内側のラプラシアンの分散. これより小さいとぼけているので撮らない
GRID = 3  # 区画 (3×3)


# ---- 角を探す ------------------------------------------------------------------------------

def find_corners_live(gray):
    """撮影中の毎コマ用 (速さ優先). NORMALIZE_IMAGE を付けると依頼 322 の desk_a3.png で見つからない (試した)."""
    ok, c = cv2.findChessboardCornersSB(gray, PATTERN, flags=cv2.CALIB_CB_EXHAUSTIVE)
    if ok and c is not None and len(c) == N_CORNERS:
        return c.reshape(-1, 2)
    return None


def find_corners_precise(gray):
    """計算用 (正確さ優先). 依頼 322 の check_322_board.py と同じ探し方."""
    ok, c = cv2.findChessboardCornersSB(gray, PATTERN, flags=cv2.CALIB_CB_EXHAUSTIVE | cv2.CALIB_CB_ACCURACY)
    if ok and c is not None and len(c) == N_CORNERS:
        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


# ---- 撮った1枚の特徴 (違いの判定と区画) ----------------------------------------------------------

def outer4(pts):
    g = pts.reshape(PATTERN[1], PATTERN[0], 2)
    return np.array([g[0, 0], g[0, -1], g[-1, -1], g[-1, 0]], dtype=np.float64)


def pose_feature(pts, w, h):
    """重心 (画面に対する割合) と, 形 (外側4つの角を重心からの位置にして画面の対角線で割ったもの).
    形には大きさ (近い・遠い)・傾き・回り方が入る."""
    c = pts.mean(0)
    cen = np.array([c[0] / w, c[1] / h])
    shape = (outer4(pts) - c) / np.hypot(w, h)
    return cen, shape


def differs(feat, feats, min_move, min_shape):
    cen, shape = feat
    for c2, s2 in feats:
        move = float(np.hypot(*(cen - c2)))
        dshape = float(np.linalg.norm(shape - s2, axis=1).mean() / max(np.linalg.norm(s2, axis=1).mean(), 1e-9))
        if move < min_move and dshape < min_shape:
            return False
    return True


def sharpness(gray, pts):
    hull = cv2.convexHull(pts.astype(np.float32)).astype(np.int32)
    mask = np.zeros_like(gray)
    cv2.fillConvexPoly(mask, hull, 255)
    lap = cv2.Laplacian(gray, cv2.CV_64F)
    return float(lap[mask > 0].var())


def add_coverage(cov, pts, w, h):
    for x, y in pts:
        cx = min(GRID - 1, max(0, int(x / w * GRID)))
        cy = min(GRID - 1, max(0, int(y / h * GRID)))
        cov[cy, cx] += 1


# ---- 撮影 ----------------------------------------------------------------------------------

def check_no_reset(cam):
    """apply_and_verify が uvc-util -r を使う場面 (手首の露出が手動になっている) なら, 当てる前に止める."""
    doc = load_lock(cam)
    if doc["exposure_auto"]:
        dev = find_device(cam)
        got = get_value(dev, AE_MODE)
        if got != AE_AUTO:
            raise CameraLockError(f"{cam} の {AE_MODE} が {got} (自動の {AE_AUTO} ではない). ここでは uvc-util -r を"
                                  f"使わないので止める. カメラを挿し直すなどで自動に戻してから走らせる")
    return doc


def draw_overlay(vis, n, target, cov, status, pts):
    h, w = vis.shape[:2]
    over = vis.copy()
    for gy in range(GRID):
        for gx in range(GRID):
            x0, y0 = gx * w // GRID, gy * h // GRID
            x1, y1 = (gx + 1) * w // GRID, (gy + 1) * h // GRID
            k = int(cov[gy, gx])
            if k:
                # 角の数で濃さを変える (54点 = 1枚分を目安に, 3枚分で一番濃い)
                a = min(1.0, k / (3 * N_CORNERS))
                cv2.rectangle(over, (x0, y0), (x1, y1), (0, int(120 + 135 * a), 0), -1)
    vis[:] = cv2.addWeighted(over, 0.25, vis, 0.75, 0)
    for i in range(1, GRID):
        cv2.line(vis, (i * w // GRID, 0), (i * w // GRID, h), (200, 200, 200), 1)
        cv2.line(vis, (0, i * h // GRID), (w, i * h // GRID), (200, 200, 200), 1)
    for gy in range(GRID):
        for gx in range(GRID):
            k = int(cov[gy, gx])
            txt = f"{k // N_CORNERS}" if k else "-"
            col = (0, 255, 0) if k else (0, 0, 255)
            cv2.putText(vis, txt, (gx * w // GRID + 6, gy * h // GRID + 22), cv2.FONT_HERSHEY_SIMPLEX, 0.6, col, 2)
    if pts is not None:
        cv2.drawChessboardCorners(vis, PATTERN, pts.reshape(-1, 1, 2).astype(np.float32), True)
    cv2.rectangle(vis, (0, h - 30), (w, h), (0, 0, 0), -1)
    cv2.putText(vis, f"{n}/{target}  {status}", (8, h - 9), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 255, 255), 1)
    cv2.putText(vis, "space=save  q=quit", (w - 175, h - 9), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (180, 180, 180), 1)


def existing_frames(frames_dir, cam):
    return sorted(frames_dir.glob(f"{cam}_*.png"))


def capture(args, frames_dir):
    """撮る. test_frames > 0 なら, そのコマ数だけ回して閉じる (保存しない)."""
    doc = check_no_reset(args.cam)
    applied = apply_and_verify(keys=(args.cam,))
    print(f"{args.cam} の固定の値:", json.dumps(applied, ensure_ascii=False))
    index = opencv_index(args.cam)
    cap = open_cap(index)  # 640×480・30fps・MJPG
    win = f"calib {args.cam} ({args.board})"
    try:
        info = {"opencv_index": index, "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)}
        meta = {"camera": args.cam, "camera_name": doc.get("device", {}).get("name"),
                "name_contains": CAMERAS[args.cam], "lock_file_time": doc.get("time"),
                "lock_applied": applied.get(args.cam), "cap": info, "board": args.board,
                "square_mm": BOARDS[args.board], "time": datetime.now().isoformat(timespec="seconds")}
        print("開いたカメラ:", json.dumps(info, ensure_ascii=False))
        time.sleep(0.5)
        for _ in range(DISCARD):
            cap.read()
        if not args.test_frames:
            frames_dir.mkdir(parents=True, exist_ok=True)
            (frames_dir / "capture_meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2) + "\n")
        # すでに撮ってある画像も, 違いの判定と区画に入れる (続きから撮れる)
        feats, cov = [], np.zeros((GRID, GRID), dtype=np.int64)
        olds = existing_frames(frames_dir, args.cam) if frames_dir.exists() else []
        for p in olds:
            g = cv2.imread(str(p), cv2.IMREAD_GRAYSCALE)
            if g is None:
                continue
            pts = find_corners_live(g)
            if pts is not None:
                feats.append(pose_feature(pts, g.shape[1], g.shape[0]))
                add_coverage(cov, pts, g.shape[1], g.shape[0])
        n = len(olds)
        if n:
            print(f"frames/ にすでに {n} 枚ある. 続きから撮る")
        prev, count, last_save, status = None, 0, 0.0, ""
        while True:
            ok, frame = cap.read()
            if not ok or frame is None:
                raise RuntimeError("コマが取れない")
            count += 1
            h, w = frame.shape[:2]
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            pts = find_corners_live(gray)
            save = False
            if pts is None:
                status = "no board"
            else:
                still = prev is not None and float(np.linalg.norm(pts - prev, axis=1).mean()) <= args.max_still_px
                sharp = sharpness(gray, pts)
                feat = pose_feature(pts, w, h)
                new = differs(feat, feats, args.min_move, args.min_shape)
                if not still:
                    status = "moving"
                elif sharp < args.min_sharp:
                    status = f"blurry ({sharp:.0f})"
                elif not new:
                    status = "same as taken - move/tilt"
                else:
                    status = "ok"
                    # 保存の直後の同じ姿勢を二重に撮らないよう 0.5 秒あける
                    save = time.monotonic() - last_save > 0.5
            prev = pts
            key = cv2.waitKey(1) & 0xFF
            if key == ord(" "):
                if pts is None:
                    print("角が54点そろっていないので保存しない")
                else:
                    save = True
            if save and not args.test_frames:
                n += 1
                name = f"{args.cam}_{n:03d}_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')[:-3]}.png"
                cv2.imwrite(str(frames_dir / name), frame)  # 元の画像のまま
                feats.append(pose_feature(pts, w, h))
                add_coverage(cov, pts, w, h)
                last_save = time.monotonic()
                print(f"保存 {n}/{args.target}: {name}")
            vis = frame.copy()
            draw_overlay(vis, n, args.target, cov, status, pts)
            cv2.imshow(win, vis)
            if key == ord("q"):
                break
            if args.test_frames and count >= args.test_frames:
                print(f"試し: {count} コマ回して閉じる (最後の状態: {status or '-'})")
                break
    finally:
        cap.release()
        cv2.destroyAllWindows()
        for _ in range(5):
            cv2.waitKey(1)
    return n


# ---- 計算 ----------------------------------------------------------------------------------

def run_calibration(objs, imgs, size):
    rms, K, dist, rvecs, tvecs = cv2.calibrateCamera(objs, imgs, size, None, None)
    per = []
    for o, i, r, t in zip(objs, imgs, rvecs, tvecs):
        proj, _ = cv2.projectPoints(o, r, t, K, dist)
        per.append(float(np.sqrt(np.mean(np.sum((proj.reshape(-1, 2) - i.reshape(-1, 2)) ** 2, axis=1)))))
    return float(rms), K, dist.reshape(-1), per


def calib_doc(rms, K, dist, per, names, size):
    w, h = size
    fx, fy, cx, cy = float(K[0, 0]), float(K[1, 1]), float(K[0, 2]), float(K[1, 2])
    return {"rms_px": round(rms, 4),
            "camera_matrix": [[float(v) for v in row] for row in K],
            "fx": fx, "fy": fy, "cx": cx, "cy": cy,
            # 画角 (度): 歪みを除いたピンホールとして
            "fov_deg": {"horizontal": float(np.degrees(2 * np.arctan(w / (2 * fx)))),
                        "vertical": float(np.degrees(2 * np.arctan(h / (2 * fy)))),
                        "diagonal": float(np.degrees(2 * np.arctan(np.hypot(w / (2 * fx), h / (2 * fy)))))},
            "dist_coeffs": [float(v) for v in dist[:5]],
            "dist_coeffs_names": ["k1", "k2", "p1", "p2", "k3"],
            "per_view_error_px": [{"file": n, "error": round(e, 4)} for n, e in zip(names, per)],
            "n_used": len(names)}


def calibrate(args, out, frames_dir):
    files = existing_frames(frames_dir, args.cam) if frames_dir.exists() else []
    if args.calibrate_only and not files:
        # --calibrate-only では名前の決まりに合わない画像 (依頼 322 の desk_a3.png など) も使う
        files = sorted(p for p in frames_dir.glob("*.png"))
    if not files:
        print(f"{frames_dir} に画像がない. 計算しない")
        return 2
    square = BOARDS[args.board]
    objp = np.zeros((N_CORNERS, 3), np.float32)
    objp[:, :2] = np.mgrid[0:PATTERN[0], 0:PATTERN[1]].T.reshape(-1, 2) * square
    objs, imgs, names, skipped, size, methods = [], [], [], [], None, {}
    for p in files:
        img = cv2.imread(str(p))
        if img is None:
            skipped.append({"file": p.name, "why": "読めない"})
            continue
        s = (img.shape[1], img.shape[0])
        if size is None:
            size = s
        elif s != size:
            skipped.append({"file": p.name, "why": f"大きさが違う {s}"})
            continue
        pts, method = find_corners_precise(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY))
        if pts is None:
            skipped.append({"file": p.name, "why": "角が54点そろわない"})
            continue
        objs.append(objp.copy())
        imgs.append(pts.reshape(-1, 1, 2).astype(np.float32))
        names.append(p.name)
        methods[method] = methods.get(method, 0) + 1
    print(f"画像 {len(files)} 枚 → 角がそろった {len(names)} 枚 (外した {len(skipped)} 枚)")
    if not names:
        print("角がそろった画像がない. 計算しない")
        return 2
    if len(names) < 10:
        print(f"注意: {len(names)} 枚では値が安定しない (目安は {TARGET} 枚・少なくとも 10 枚)")
    rms, K, dist, per = run_calibration(objs, imgs, size)
    first = calib_doc(rms, K, dist, per, names, size)
    print(f"1回目: 誤差 {rms:.4f} px ({len(names)} 枚)")
    dropped = []
    if args.drop_worst:
        if len(names) - args.drop_worst < 3:
            print(f"--drop-worst {args.drop_worst} を外すと {len(names) - args.drop_worst} 枚になるので外さない")
        else:
            worst = sorted(range(len(names)), key=lambda i: -per[i])[:args.drop_worst]
            dropped = [{"file": names[i], "error": round(per[i], 4)} for i in sorted(worst, key=lambda i: -per[i])]
            keep = [i for i in range(len(names)) if i not in set(worst)]
            objs, imgs, names = [objs[i] for i in keep], [imgs[i] for i in keep], [names[i] for i in keep]
            rms, K, dist, per = run_calibration(objs, imgs, size)
            print(f"誤差の大きい {len(dropped)} 枚を外して計算し直し: 誤差 {rms:.4f} px ({len(names)} 枚)")
    final = calib_doc(rms, K, dist, per, names, size)
    meta_p = frames_dir / "capture_meta.json"
    meta = json.loads(meta_p.read_text()) if meta_p.exists() else {}
    doc = {"camera": args.cam,
           "camera_name": meta.get("camera_name") or load_lock(args.cam).get("device", {}).get("name"),
           "time": datetime.now().isoformat(timespec="seconds"),
           "made_by": "so101/calib_camera.py (依頼 323)",
           "image_size": list(size),
           "board": {"name": args.board, "inner_corners": list(PATTERN), "squares": [PATTERN[0] + 1, PATTERN[1] + 1],
                     "square_mm": square},
           "lock_applied": meta.get("lock_applied"),
           "lock_file_time": meta.get("lock_file_time"),
           "capture": meta.get("cap"),
           "capture_time": meta.get("time"),
           "corner_method": methods,
           "frames_dir": str(frames_dir),
           "skipped": skipped,
           "drop_worst": args.drop_worst,
           "dropped": dropped,
           **final}
    if dropped:
        doc["before_drop"] = {"rms_px": first["rms_px"], "n_used": first["n_used"],
                              "camera_matrix": first["camera_matrix"], "dist_coeffs": first["dist_coeffs"]}
    out.mkdir(parents=True, exist_ok=True)
    jp = out / f"camera_{args.cam}.json"
    if jp.exists():  # 前の結果は消さずに写しておく
        bak = out / f"camera_{args.cam}.prev_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        shutil.copy2(jp, bak)
        print(f"前の結果を {bak.name} に写した")
    jp.write_text(json.dumps(doc, ensure_ascii=False, indent=2) + "\n")
    # 歪みを補正した確認用の画像: 使った画像のうち誤差の一番小さい1枚. 左 = 元, 右 = 補正 (黒い縁なし)
    best = names[int(np.argmin(per))]
    img = cv2.imread(str(frames_dir / best))
    newK, _ = cv2.getOptimalNewCameraMatrix(K, dist, size, 0, size)
    und = cv2.undistort(img, K, dist, None, newK)
    for im, label in ((img, "original"), (und, "undistorted")):
        cv2.putText(im, f"{label}  {best}", (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (0, 0, 255), 2)
    cv2.imwrite(str(out / "undistort_check.png"), np.hstack([img, und]))
    print(json.dumps({k: doc[k] for k in ("rms_px", "n_used", "fx", "fy", "cx", "cy", "fov_deg", "dist_coeffs")},
                     ensure_ascii=False, indent=2))
    print(f"書いた: {jp}, {out / 'undistort_check.png'}")
    return 0


def main():
    ap = argparse.ArgumentParser(description="SO-101 のカメラのレンズを測る (依頼 323)")
    ap.add_argument("--cam", required=True, choices=sorted(CAMERAS))
    ap.add_argument("--board", required=True, choices=sorted(BOARDS), help="a3 = 1マス 38mm, a4 = 1マス 25mm")
    ap.add_argument("--out", required=True, help="出力のフォルダ (frames/ はこの下)")
    ap.add_argument("--calibrate-only", action="store_true", help="撮らずに frames/ の画像から計算だけする")
    ap.add_argument("--drop-worst", type=int, default=0, help="誤差の大きい画像を N 枚外して計算し直す")
    ap.add_argument("--target", type=int, default=TARGET, help="目標の枚数 (窓に出すだけ. 超えても撮れる)")
    ap.add_argument("--min-move", type=float, default=MIN_MOVE)
    ap.add_argument("--min-shape", type=float, default=MIN_SHAPE)
    ap.add_argument("--max-still-px", type=float, default=MAX_STILL_PX)
    ap.add_argument("--min-sharp", type=float, default=MIN_SHARP)
    ap.add_argument("--test-frames", type=int, default=0,
                    help="試し: カメラを開いて窓を出し, このコマ数だけ回して閉じる (保存も計算もしない)")
    args = ap.parse_args()
    out = Path(args.out).expanduser().resolve()
    if str(out).startswith("/Volumes/"):
        print(f"--out が {out}: KIOXIA などの外付けには書かない. so101/check_323/ などに出してから写す")
        return 2
    frames_dir = out / "frames"
    if not args.calibrate_only:
        try:
            capture(args, frames_dir)
        except CameraLockError as e:
            print(f"止めた: {e}")
            return 2
        if args.test_frames:
            return 0
    return calibrate(args, out, frames_dir)


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