"""依頼 343 の確かめの後半 (yaw_check_343.py range / preview / window から呼ぶ). アームもカメラも使わない.

range: 置く範囲を広げられる所 (机側カメラの画素の格子. 12 画素ごと) を, 次の条件で調べる.
  届く: 仮の正解 (make_var_314.Truth. 今の台座で録り直したときの見込みの 13 点から作る. 画素 → 手先は 13 点の一次式,
        高さ・爪の傾きは 13 点から) で「ブロックの上」「つかむ所」が解ける. 爪の真下からの傾きは今の 13 点の最大 (36°) まで
  道: 向き -40・0・+40° で var_lib_314.make_path が通る (1 コマの動き・持ち上げ・運ぶ間の高さ・手首の回転以外の安全範囲.
      手首の回転は 案A の広げた範囲で見る. 今の範囲で入る向きは別に出す)
  安全: シム (MuJoCo. 今の台座・測った箱) で 道の上の 手首・爪・カメラから 箱 15mm・台座と肩 15mm (ブロックのまわりの間)・
        机 15mm (下ろす・閉じる・持ち上げるの間を除く)・ブロック (+10mm) 0mm (ブロックの上に来るまで) 以上
  見える: 休みの姿勢 (HOME の肩の回転 ±3°) の腕が 机側カメラの絵でブロック (向き 0・±40°) に 5% より重ならない. 画面の縁から 10 画素
          手首カメラ: 「ブロックの上」でブロックの 8 隅が 手首の絵の縁から 30 画素の内側
  足す校正の点: 条件を満たす格子の点から, 今の 13 点の囲みを広げる点を 1 つずつ選ぶ (囲みの中の格子が全部条件を満たすもののうち,
        広がる面積がいちばん大きいもの. 奥 (v < 170) は選ばない). 増えた面積が今の 2% より小さくなるか 6 点で止める.
        そのあと 広げた所 (今の囲みの外) で 仮の正解と TPS の補いの差 (つかむ所の手先 mm) がいちばん大きい所が 8 mm を超えれば
        そこ (条件を満たす格子) に 1 点足す (3 点まで)
"""
import json
import math
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
import yaw_check_343 as C  # noqa: E402

BF, PL, V, Y = C.BF, C.PL, C.V, C.Y
OUT = C.OUT
CLEAR_MM = 15.0
GRID_PX = 12
TOP_V_MIN = 170.0           # 奥 (場所1 の辺り) は広げない
ADD_MAX, ADD_AREA_MIN = 6, 0.02
TPS_ADD_MM, TPS_ADD_MAX = 8.0, 3      # 広げた所で 仮の正解との差 (つかむ所の手先) がこれより大きい所に点を足す (3 点まで)
ARM_PAN_SWING = (-3.0, 0.0, 3.0)
OCCLUDE_MAX = 0.05          # 休みの姿勢の腕がブロックの写った所に重なってよい割合 (場所4 は 3%. 今日読めている)
ARM_BODIES = ("wrist", "gripper", "moving_jaw_so101_v1", "wrist_camera_mount", "wrist_camera")
ALL_ARM = ("base", "shoulder", "upper_arm", "lower_arm") + ARM_BODIES
PATH_YAWS = (-40.0, 0.0, 40.0)
WRIST_MARGIN_PX = 30


class Geo:
    def __init__(self, sc):
        self.sc, self.m, self.d = sc, sc.m, sc.d
        import mujoco
        self.mj = mujoco
        by = lambda bodies: [g for g in range(self.m.ngeom) if self.m.body(int(self.m.geom_bodyid[g])).name in bodies]  # noqa: E731
        self.arm, self.jaw, self.base = by(ARM_BODIES), by(("gripper", "moving_jaw_so101_v1")), by(("base", "shoulder"))
        self.table = [self.m.geom("table").id]
        self.box = [self.m.geom(n).id for n in ("box_floor", "box_wall_xn", "box_wall_xp", "box_wall_yn", "box_wall_yp")]
        self.blk = [self.m.geom("block").id]
        self.ft = np.zeros(6)

    def dist(self, A, B):
        return min(self.mj.mj_geomDistance(self.m, self.d, a, b, 0.5, self.ft) for a in A for b in B) * 1000


def path_clearance(geo, res, xy, yaw, step=3):
    """1 本の道の 距離 (mm). ブロックは xy・yaw に置く"""
    sc = geo.sc
    sc.block(xy, yaw)
    path, fr = res["path"], res["frames"]
    out = {"table": 1e9, "grasp_table": 1e9, "box": 1e9, "base": 1e9, "block_pad10": 1e9}
    for k in range(0, len(path), step):
        sc.pose(path[k])
        before = k <= fr["ABOVE_BLOCK"]
        grasp = fr["ABOVE_BLOCK"] < k < fr["LIFT"]
        dt = geo.dist(geo.arm, geo.table)
        if grasp:
            out["grasp_table"] = min(out["grasp_table"], dt)
        else:
            out["table"] = min(out["table"], dt)
        out["box"] = min(out["box"], geo.dist(geo.arm, geo.box))
        if fr["ABOVE_BLOCK"] - 15 <= k <= fr["LIFT"] + 10:     # 台座・肩: ブロックのまわりで (HOME の姿勢そのものが 15.6 mm)
            out["base"] = min(out["base"], geo.dist(geo.arm, geo.base))
        if before:
            out["block_pad10"] = min(out["block_pad10"], geo.dist(geo.arm, geo.blk) - 10.0)
    sc.block([1000, 1000], 0)
    return {k: round(float(v), 1) for k, v in out.items()}


def arm_rest_mask(sc):
    """休みの姿勢 (HOME の肩の回転 ±6°) の腕が 机側カメラに写る所 (640×480 の bool)"""
    sc.block([1000, 1000], 0)
    m = None
    for dp in ARM_PAN_SWING:
        q = V.HOME.copy()
        q[0] += dp
        sc.pose(q)
        k = sc.rp.cr.seg_bodies(sc.d, "desk", ALL_ARM)
        m = k if m is None else (m | k)
    return m


def block_hull_mask(cam, xy, yaw):
    import cv2
    import sim_330 as S
    px = S.project_arm(S.box_corners(xy, yaw, [Y.BLOCK_MM] * 2, 0, Y.BLOCK_MM), cam)
    m = np.zeros((480, 640), np.uint8)
    cv2.fillConvexPoly(m, np.round(cv2.convexHull(px.astype(np.float32))).astype(np.int32), 1)
    return m > 0, px


def wrist_view(sc, q6, xy, yaw):
    """「ブロックの上」で ブロックの 8 隅が手首の絵の縁から何画素内側か (負 = 外. カメラの後ろなら -999)"""
    import cv2
    import sim_330 as S
    sc.pose(q6)
    cam = sc.wrist_cam()
    c8 = S.box_corners(xy, yaw, [Y.BLOCK_MM] * 2, 0, Y.BLOCK_MM)
    Pc = (c8 - cam["pos_arm_mm"]) @ cam["R_arm"]
    if (Pc[:, 2] < 5).any():
        return -999.0
    px, _ = cv2.projectPoints(Pc, np.zeros(3), np.zeros(3), cam["K"], cam["D"])
    px = px.reshape(-1, 2)
    return float(min(px[:, 0].min(), 640 - px[:, 0].max(), px[:, 1].min(), 480 - px[:, 1].max()))


class Checker:
    def __init__(self, render=True):
        import make_var_314 as MV
        import run_so101_policy as R
        self.chain = V.load_urdf_chain(V.URDF)
        self.lo, self.hi, _ = R.load_safe_range(R.DEFAULT_RAW)
        self.lo_w, self.hi_w = self.lo.copy(), self.hi.copy()
        self.lo_w[4], self.hi_w[4] = C.WIDE_ROLL
        self.base_pts = C.predicted_points()
        self.truth = MV.Truth(self.base_pts, self.chain)
        self.sc = C.Scene(render=render)
        self.geo = Geo(self.sc)
        self.cam = Y.desk_cam()
        self.rest = arm_rest_mask(self.sc) if render else None
        self.tilt_max = max(Y.tool_tilt_deg(self.chain, p["grasp"]) for p in self.base_pts)

    def point(self, uv, name="X"):
        t = self.truth(np.asarray(uv, np.float64))
        if t is None:
            return None
        return {"name": name, "kind": "extra", "u": float(uv[0]), "v": float(uv[1]),
                "above": np.r_[t[0], V.GRIP["ABOVE_BLOCK"]].round(3).tolist(), "grasp": np.r_[t[1], V.GRIP["GRASP_OPEN"]].round(3).tolist()}

    def check(self, uv, full=True):
        """→ dict (ok: 条件を全部満たすか, 各条件の値)"""
        uv = np.asarray(uv, np.float64)
        r = {"pixel": uv.round(1).tolist(), "ok": False}
        if PL.in_zone(uv, PL.BOX_ZONE):
            r["why"] = "箱の所"
            return r
        pt = self.point(uv)
        if pt is None:
            r["why"] = "届かない (仮の正解が解けない)"
            return r
        qg = np.array(pt["grasp"][:5])
        r["tilt"] = round(Y.tool_tilt_deg(self.chain, qg), 1)
        if r["tilt"] > self.tilt_max + 0.5:
            r["why"] = f"爪が傾きすぎ ({r['tilt']}°)"
            return r
        xy = Y.pixel_to_desk_mm(self.cam, uv)
        r["xy_mm"] = np.round(xy, 1).tolist()
        # 机側カメラ (休みの姿勢の腕に隠れない・画面の中)
        if self.rest is not None:
            worst = 0.0
            for yw in PATH_YAWS:
                hm, px = block_hull_mask(self.cam, xy, yw)
                inside = float(min(px[:, 0].min(), 640 - px[:, 0].max(), px[:, 1].min(), 480 - px[:, 1].max()))
                if inside < 10:
                    r["why"] = "机側カメラの画面の縁"
                    return r
                worst = max(worst, float((hm & self.rest).sum()) / max(1, hm.sum()))
            r["desk_occluded"] = round(worst, 3)
            if worst > OCCLUDE_MAX:
                r["why"] = f"休みの姿勢の腕に隠れる ({worst:.0%})"
                return r
        # 今の範囲で入る向き (手首の回転だけ)
        ok_y = []
        for yw in C.YAWS:
            da, _ = Y.roll_for_yaw(self.chain, pt["above"], yw)
            dg, _ = Y.roll_for_yaw(self.chain, qg, yw)
            if self.lo[4] <= pt["above"][4] + da <= self.hi[4] and self.lo[4] <= qg[4] + dg <= self.hi[4]:
                ok_y.append(yw)
        r["yaw_ok_now"] = [min(ok_y), max(ok_y)] if ok_y else None
        # 道 (手首の回転は広げた範囲で)
        near = any(np.hypot(p["u"] - uv[0], p["v"] - uv[1]) < V.MIN_POINT_GAP_PX for p in self.base_pts)
        gm = V.GraspMap(self.base_pts if near else self.base_pts + [pt])
        cl = {}
        for yw in PATH_YAWS:
            res = V.make_path(gm, uv, self.chain, self.lo_w, self.hi_w, yaw=yw)
            if not res["ok"]:
                r["why"] = f"道が通らない (向き {yw:+.0f}°: {res['why']})"
                return r
            if not full:
                continue
            c = path_clearance(self.geo, res, xy, yw)
            for k, v in c.items():
                cl[k] = min(cl.get(k, 1e9), v)
            wv = wrist_view(self.sc, res["keyframes"][1]["pose"], xy, yw)
            cl["wrist_view_px"] = min(cl.get("wrist_view_px", 1e9), round(wv, 1))
        r["clear"] = cl
        if full:
            bad = [f"{k} {cl[k]}" for k, lim in (("table", CLEAR_MM), ("box", CLEAR_MM), ("base", CLEAR_MM), ("block_pad10", 0.0),
                                                ("wrist_view_px", WRIST_MARGIN_PX)) if cl[k] < lim]
            if bad:
                r["why"] = "近い・見えない: " + ", ".join(bad)
                return r
        r["ok"] = True
        r["why"] = ""
        return r


def area(h):
    x, y = h[:, 0], h[:, 1]
    return 0.5 * abs(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))


def range_(argv):
    import cv2
    ck = Checker(render=True)
    base = ck.base_pts
    H0 = V.convex_hull([[p["u"], p["v"]] for p in base])
    grid = [(u, v) for v in range(GRID_PX // 2, 480, GRID_PX) for u in range(GRID_PX // 2, 640, GRID_PX)]
    cells = {}
    t0 = __import__("time").time()
    cache = OUT / "range_cells_343.json"         # 格子を調べた結果 (12 分ほどかかるので, あれば使う. 消せば調べ直す)
    if cache.exists():
        cells = {tuple(c["pixel"]): {**c, "pixel": c["pixel"]} for c in json.loads(cache.read_text())}
        print(f"[RANGE] 調べた結果を使う: {cache.relative_to(C.REPO)}")
    else:
        for i, uv in enumerate(grid):
            if V.hull_margin(H0, uv) < -150:        # 今の囲みから遠い所は見ない
                continue
            cells[uv] = ck.check(uv)
            if i % 200 == 0:
                print(f"  {i}/{len(grid)}  {__import__('time').time() - t0:.0f} 秒", flush=True)
        OUT.mkdir(parents=True, exist_ok=True)
        cache.write_text(json.dumps([{**r, "pixel": list(uv)} for uv, r in cells.items()], ensure_ascii=False, default=float) + "\n")
    okset = {uv for uv, r in cells.items() if r["ok"]}
    print(f"[RANGE] 調べた {len(cells)} 点. 条件を満たす {len(okset)} 点. {__import__('time').time() - t0:.0f} 秒")
    excluded = lambda uv: PL.in_zone(uv, PL.BOX_ZONE)  # noqa: E731

    # 広げた所にあってはいけない格子 (条件を満たさない所. 箱の所と, 休みの姿勢の腕に隠れる所 (割り振りで置かない) と,
    # 今の 13 点の囲みの中 (今までどおり. 中の様子は inside_now_bad に出す) は除く)
    badpx = np.array([uv for uv, r in cells.items() if not r["ok"] and not excluded(uv) and V.hull_margin(H0, uv) < 0
                      and not r.get("why", "").startswith("休みの姿勢の腕")], np.float64).reshape(-1, 2)

    def hull_ok(pts):
        h = V.convex_hull(pts)
        if not len(badpx):
            return True
        m = np.full(len(badpx), np.inf)
        for a, b in zip(h, np.roll(h, -1, 0)):
            e = b - a
            m = np.minimum(m, (e[0] * (badpx[:, 1] - a[1]) - e[1] * (badpx[:, 0] - a[0])) / np.linalg.norm(e))
        return bool((m < 0).all())

    P = [[p["u"], p["v"]] for p in base]
    inside_bad = [(uv, cells[uv]["why"]) for uv in cells if V.hull_margin(H0, uv) >= 0 and not excluded(uv) and not cells[uv]["ok"]
                  and not cells[uv].get("why", "").startswith("休みの姿勢の腕")]
    print(f"[RANGE] 今の 13 点の囲みの中で条件を満たさない格子 {len(inside_bad)}: {inside_bad[:4]}")
    added = []
    cand = [uv for uv in okset if uv[1] >= TOP_V_MIN and V.hull_margin(H0, uv) < -GRID_PX and cells[uv].get("desk_occluded", 1) == 0]
    for _ in range(ADD_MAX):
        a0 = area(V.convex_hull(P))
        best = None
        for uv in cand:
            Q = P + [list(uv)]
            g = area(V.convex_hull(Q)) - a0
            if best is not None and g <= best[1]:
                continue
            if hull_ok(Q):
                best = (uv, g)
        if best is None or best[1] < ADD_AREA_MIN * area(H0):
            break
        P.append(list(best[0]))
        added.append({"pixel": list(best[0]), "area_gain_px2": round(best[1])})
        cand = [uv for uv in cand if V.hull_margin(V.convex_hull(P), uv) < -GRID_PX]
        print(f"[RANGE] 足す点 {best[0]}  増えた面積 {best[1]:.0f} 画素²")
    # 名前と場所の言い方
    A, _ = V.pixel_mm_affine(base, ck.chain)
    mmpp = float(np.sqrt(abs(np.linalg.det(A[:, :2]))))
    places = [p for p in base if p["kind"] == "place"]
    new_pts = []
    for k, a in enumerate(added):
        pt = ck.point(a["pixel"], f"E{9 + k}")
        pt["where"] = PL.where_text(a["pixel"], places, mmpp)
        pt["label"] = label_of(a["pixel"], base)
        pt["check"] = cells[tuple(a["pixel"])]
        new_pts.append(pt)
    # TPS の補いの差 (仮の正解). 今の 13 点 / 足したあと
    import make_var_314 as MV
    synth13 = MV.synth_points(ck.truth, [[p["u"], p["v"]] for p in base], "T")
    synth13 = [dict(p) if s_ is None else {**s_, "name": p["name"], "kind": p["kind"]} for s_, p in zip(synth13, base)]  # 解けない点は見込みのまま
    lay_new = synth13 + [{**p} for p in new_pts]
    h13, hnew = V.convex_hull([[p["u"], p["v"]] for p in synth13]), V.convex_hull([[p["u"], p["v"]] for p in lay_new])
    err13 = MV.grid_error(synth13, ck.truth, "tps", h13)
    errnew = MV.grid_error(lay_new, ck.truth, "tps", hnew)
    clear_set = {uv for uv in okset if cells[uv].get("desk_occluded", 1) == 0}     # 校正の点は腕に少しも重ならない所に
    for _ in range(TPS_ADD_MAX):
        worst = tps_worst_mm(lay_new, ck.truth, hnew, H0, clear_set)
        if worst["max_mm"] <= TPS_ADD_MM:
            break
        uv = worst["pixel"]
        pt = ck.point(uv, f"E{9 + len(new_pts)}")
        pt.update({"where": PL.where_text(uv, places, mmpp), "label": label_of(uv, base) + " (TPS の差が大きい所)",
                   "check": cells[tuple(uv)], "tps_err_before_mm": worst["max_mm"]})
        new_pts.append(pt)
        lay_new.append(dict(pt))
        print(f"[RANGE] TPS の差 {worst['max_mm']} mm の所に足す {pt['name']} {tuple(uv)}")
    hnew = V.convex_hull([[p["u"], p["v"]] for p in lay_new])
    errnew = MV.grid_error(lay_new, ck.truth, "tps", hnew)
    worst = tps_worst_mm(lay_new, ck.truth, hnew, H0, okset)
    loo13 = V.leave_one_out(synth13, names=[p["name"] for p in places], chain=ck.chain)
    loonew = V.leave_one_out(lay_new, names=[p["name"] for p in places], chain=ck.chain)
    loo_new_pts = V.leave_one_out(lay_new, names=[p["name"] for p in new_pts], chain=ck.chain)
    a13, anew = area(H0), area(V.convex_hull([[p["u"], p["v"]] for p in base + new_pts]))
    n_pts = len(base) + len(new_pts)
    doc = {"made_by": "so101/ideal_var/yaw_check_343.py range (依頼 343 の 7)", "how": __doc__,
           "grid_px": GRID_PX, "tilt_max_deg": round(ck.tilt_max, 1), "wide_roll": C.WIDE_ROLL,
           "n_checked": len(cells), "n_ok": len(okset),
           "inside_now_bad": [{"pixel": list(uv), "why": w} for uv, w in inside_bad],
           "area_px2": {"now_13": round(a13), "new": round(anew), "ratio": round(anew / a13, 3)},
           "area_mm2_approx": {"now_13": round(a13 * mmpp ** 2), "new": round(anew * mmpp ** 2)},
           "new_points": new_pts, "tps_grid_error_synthetic": {"now_13": err13, "new": errnew, "worst_new": worst},
           "loo_places_synthetic": {"now_13": loo13, "new": loonew}, "loo_new_points_synthetic": loo_new_pts,
           "minutes": {"per_point": [1.0, 1.5], "added_points": len(new_pts),
                       "added_minutes": [round(len(new_pts) * 1.0, 1), round(len(new_pts) * 1.5, 1)],
                       "calib_total_minutes": [round(n_pts * 1.0, 1), round(n_pts * 1.5, 1)]},
           "cells": [{"pixel": list(uv), **{k: v for k, v in r.items() if k != "pixel"}} for uv, r in cells.items()]}
    C.dump("range_343.json", doc)
    rec = recommend_doc(base, new_pts)
    C.dump("calib_points_343.json", rec)
    draw_range(ck, cells, base, new_pts, OUT / "range_343.png")
    print(f"[RANGE] 面積 {a13:.0f} → {anew:.0f} 画素² (×{anew / a13:.2f}). 足す点 {len(new_pts)}: "
          + ", ".join(f"{p['name']} ({p['u']:.0f}, {p['v']:.0f}) {p['where']}" for p in new_pts))
    print(f"[RANGE] TPS の差 (仮の正解. 関節ごとの最大) 今 {err13['max_by_joint']} / 足したあと {errnew['max_by_joint']}")
    return 0


def tps_worst_mm(lay, truth, hull, H0, okset):
    """広げた所 (H0 の外・hull の中) の条件を満たす格子で, TPS で補ったつかむ所と仮の正解の手先の差 (mm) がいちばん大きい所"""
    m = V.GraspMap(lay)
    best = {"max_mm": 0.0, "pixel": None}
    for uv in okset:
        p = np.array(uv, np.float64)
        if V.hull_margin(H0, p) >= 0 or V.hull_margin(hull, p) < 0:
            continue
        t = truth(p)
        if t is None:
            continue
        y = m.f(p)
        e = float(np.linalg.norm(V.tcp_mm(truth.chain, y[5:]) - V.tcp_mm(truth.chain, t[1])))
        if e > best["max_mm"]:
            best = {"max_mm": round(e, 1), "pixel": list(uv)}
    return best


def tps_worst(lay, truth, hull, step=12):
    m = V.GraspMap(lay)
    best = {"max_deg": 0.0, "pixel": None}
    for u in range(0, 640, step):
        for v in range(0, 480, step):
            p = np.array([u, v], np.float64)
            if V.hull_margin(hull, p) < 0 or PL.in_zone(p, PL.BOX_ZONE):
                continue
            y, t = m.f(p), truth(p)
            if t is None:
                continue
            e = float(np.abs(np.r_[y[:5] - t[0], y[5:] - t[1]]).max())
            if e > best["max_deg"]:
                best = {"max_deg": round(e, 2), "pixel": [u, v]}
    return best


def label_of(uv, base):
    u, v = uv
    if u < 200:
        return "左 (E7・E8 の外)" if v >= 200 else "左上"
    if v >= 330:
        return "手前"
    if u >= 330:
        return "右下 (E5 と箱の間・台座の右)"
    return "下"


def recommend_doc(base, new_pts):
    """session_315.sh が読む勧める点 (依頼 314 の calib_points_314.json と同じ形 + E9〜). above・grasp は --dry-fake の仮の値"""
    rec = json.loads(BF.RECOMMEND.read_text())
    pts = list(rec["points"])
    for p in new_pts:
        pts.append({k: p[k] for k in ("name", "u", "v", "label", "where", "above", "grasp")})
    return {"request": 343, "note": rec["note"] + " 依頼 343: E9〜 を足した (置く範囲を届く限界まで広げる. yaw_check_343.py range)",
            "fake_note": rec["fake_note"] + " E9〜 は 今の台座で録り直したときの見込みの 13 点から作った仮の正解",
            "from": str(BF.RECOMMEND), "points": pts, "places": rec["places"]}


def draw_range(ck, cells, base, new_pts, path):
    import cv2
    img = cv2.resize(cv2.imread(str(BF.DESK_PHOTO)), (640, 480))
    over = img.copy()
    for uv, r in cells.items():
        col = (0, 200, 0) if r["ok"] else ((0, 0, 220) if not r.get("why", "").startswith("休みの姿勢") else (200, 120, 0))
        cv2.rectangle(over, (uv[0] - GRID_PX // 2, uv[1] - GRID_PX // 2), (uv[0] + GRID_PX // 2 - 1, uv[1] + GRID_PX // 2 - 1), col, -1)
    img = cv2.addWeighted(over, 0.25, img, 0.75, 0)
    h0 = V.convex_hull([[p["u"], p["v"]] for p in base]).astype(np.int32)
    h1 = V.convex_hull([[p["u"], p["v"]] for p in base + new_pts]).astype(np.int32)
    cv2.polylines(img, [h0], True, (90, 90, 90), 2, cv2.LINE_AA)
    cv2.polylines(img, [h1], True, (0, 160, 0), 2, cv2.LINE_AA)
    for p in base + new_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, "green = ok  red = not ok  orange = hidden by arm at rest  gray = now (13)  green line = new", (8, 16),
                cv2.FONT_HERSHEY_SIMPLEX, 0.42, (0, 0, 0), 1, cv2.LINE_AA)
    cv2.imwrite(str(path), img)
    print("[OUT ]", path)


def main(argv):
    step = argv[0]
    import yaw_check3_343 as C3
    return {"range": range_, "preview": C3.preview, "window": C3.window}[step](argv[1:])
