#!/usr/bin/env python3
"""依頼 373: so101f の実機の試し (session_373.sh) で, 1 回ごとに机のカメラの映像に「置く所」を重ねて窓に出す.

置く所は so101b の試しと同じ 場所1〜5 の目印 (画素は依頼 315 の校正の点 calib_points_315.json の place1〜place5. 読むだけ).
  - 水色の丸 (二重) = この回の場所の目印. 丸の中の四角 (水色) = まっすぐ置いたときの向き (画像の縦横にそろえた形)
  - 十字 = カメラが読んだ赤いブロックの所 (block_pixel_314.detect). 上の帯は 丸の近くなら緑・離れていれば黄
  - 帯の色は目安だけ. Enter はいつでも進む (止める条件は足さない. 依頼 373)
Enter は窓でもターミナルでもよい (窓は Enter か Space, ターミナルは Enter). s で止める.
session_351.sh の窓 (preview_315.py) と同じく, 机のカメラはこの窓の間だけ開き, 進むときに閉じてから終わる
(このあと run_so101_policy.py がカメラ 2 台を開く).

終了コード: 0 = 進む / 1 = s で止めた / 2 = カメラが開けない

  python so101/check_373/place_window_373.py --place 3 --count 7/30 --calib <calib.json>                   本番 (窓を出す)
  python so101/check_373/place_window_373.py --place 3 --count 7/30 --calib <calib.json> --fake-png out.png  窓を出さずに 1 枚描く
"""
import argparse
import json
import sys
import time
from datetime import datetime
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE.parent))
sys.path.insert(0, str(HERE.parent / "ideal_var"))
import block_pixel_314 as BP  # noqa: E402
import preview_315 as PV  # noqa: E402

WIN = "SO-101 373: place the block"
SCALE = PV.SCALE
NEAR_PX = PV.BLOCK_SIDE_PX           # 十字が丸の中心からこれ以内なら帯を緑に (目安だけ)
EXIT_GO, EXIT_STOP, EXIT_NO_CAMERA = 0, 1, 2


def place_pixel(calib, place):
    doc = json.loads(Path(calib).read_text())
    for p in doc["points"]:
        if p.get("kind") == "place" and p.get("name") == f"place{place}":
            return float(p["u"]), float(p["v"])
    raise SystemExit(f"[ERROR] 校正の点に place{place} がない: {calib}")


def draw(rgb, uv, place, count, det, why_det):
    import cv2
    bgr = np.ascontiguousarray(rgb[..., ::-1])
    big = cv2.resize(bgr, None, fx=SCALE, fy=SCALE, interpolation=cv2.INTER_LINEAR)
    cu, cv_ = int(round(uv[0] * SCALE)), int(round(uv[1] * SCALE))
    r = int(PV.BLOCK_SIDE_PX * SCALE)
    cv2.circle(big, (cu, cv_), r, (255, 255, 0), 3, cv2.LINE_AA)
    cv2.circle(big, (cu, cv_), r + 6, (255, 255, 0), 1, cv2.LINE_AA)
    h = int(PV.BLOCK_SIDE_PX * PV.SQUARE_SCALE * SCALE / 2)
    cv2.rectangle(big, (cu - h, cv_ - h), (cu + h, cv_ + h), (255, 255, 0), 2, cv2.LINE_AA)
    near = False
    if det is not None:
        du, dv = int(round(det["u"] * SCALE)), int(round(det["v"] * SCALE))
        d = float(np.hypot(det["u"] - uv[0], det["v"] - uv[1]))
        near = d <= NEAR_PX
        col = (0, 220, 0) if near else (0, 220, 255)
        cv2.line(big, (du - 18, dv), (du + 18, dv), col, 2, cv2.LINE_AA)
        cv2.line(big, (du, dv - 18), (du, dv + 18), col, 2, cv2.LINE_AA)
        sub = f"丸の中心から {d:.0f} 画素" + ("" if near else "  (丸に寄せてください. Enter でも進めます)")
    else:
        sub = f"ブロックが見えません ({why_det})"
    band = (0, 150, 0) if near else (0, 170, 220)
    cv2.rectangle(big, (0, 0), (big.shape[1], 92), band, -1)
    return PV.put_text(big, [((14, 6), f"{count} 回目   場所{place}   ブロックはまっすぐ (四角に合わせる)", 30, (255, 255, 255)),
                             ((14, 50), f"置いたら Enter (s で止める)   {sub}", 22, (255, 255, 255))])


def say(det, uv):
    if det is None:
        print("[WINDOW] ブロックは見えていません (そのまま進みます)")
    else:
        print(f"[WINDOW] ブロックの画素 ({det['u']:.1f}, {det['v']:.1f})・丸の中心との差 "
              f"{np.hypot(det['u'] - uv[0], det['v'] - uv[1]):.0f} 画素")


def fake(args, uv):
    """窓を出さずに 1 枚 (--dry-fake). 灰色の机の丸の辺りに赤い四角を描いて読む"""
    import cv2
    rng = np.random.default_rng(args.place)
    rgb = PV.fake_desk((uv[0] + rng.uniform(-6, 6), uv[1] + rng.uniform(-6, 6)), seed=args.place)
    det, why = BP.detect(rgb, rgb=True)
    out = Path(args.fake_png)
    out.parent.mkdir(parents=True, exist_ok=True)
    cv2.imwrite(str(out), draw(rgb, uv, args.place, args.count, det, why))
    say(det, uv)
    print(f"[WINDOW] 描いた窓: {out}")
    return EXIT_GO


def live(args, uv):
    import cv2
    import camera_lock_259 as cl
    try:
        cl.apply_and_verify(("desk",))
        cap = cl.open_cap(cl.opencv_index("desk"))
    except Exception as ex:
        print(f"[ERROR] 机のカメラが開けない: {ex}")
        return EXIT_NO_CAMERA
    last = None
    try:
        cv2.namedWindow(WIN, cv2.WINDOW_AUTOSIZE)
        try:
            cv2.setWindowProperty(WIN, cv2.WND_PROP_TOPMOST, 1)
        except cv2.error:
            pass
        print(f"[WINDOW] 窓を出しました. 場所{args.place} の丸にブロックをまっすぐ置いて Enter (s で止める)")
        while True:
            ok_read, bgr = cap.read()
            if not ok_read:
                time.sleep(0.05)
                continue
            rgb = bgr[..., ::-1].copy()
            det, why = BP.detect(rgb, rgb=True)
            img = draw(rgb, uv, args.place, args.count, det, why)
            cv2.imshow(WIN, img)
            k = cv2.waitKey(30) & 0xFF
            key = {13: "", 10: "", 32: "", ord("s"): "s", ord("S"): "s"}.get(k)
            if key is None:
                key = PV.stdin_line()
            if key is None:
                continue
            if key == "s":
                print("[WINDOW] s で止めました")
                return EXIT_STOP
            last = (det, img)
            break
    finally:
        cap.release()
        cv2.destroyAllWindows()
        for _ in range(5):          # macOS は waitKey を回さないと窓が消えない
            cv2.waitKey(1)
    det, img = last
    say(det, uv)
    if args.log_dir:
        n = args.count.split("/")[0]
        PV.write_png(Path(args.log_dir) / f"n{int(n):02d}_place{args.place}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png", img)
    return EXIT_GO


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--place", type=int, choices=range(1, 6), required=True)
    ap.add_argument("--count", required=True, help="何回目か (例 7/30). 窓に出すだけ")
    ap.add_argument("--calib", required=True, help="場所1〜5 の画素がある校正の点 (calib_points_315.json. 読むだけ)")
    ap.add_argument("--log-dir", default="", help="本番で Enter で進んだときの窓を書く所 (空なら書かない)")
    ap.add_argument("--fake-png", default="", help="窓を出さずに, 灰色の机に赤い四角を描いた 1 枚をここに書く")
    args = ap.parse_args(argv)
    uv = place_pixel(args.calib, args.place)
    return fake(args, uv) if args.fake_png else live(args, uv)


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