#!/usr/bin/env python3
"""依頼 406: 回して置いたブロックを ずらした始めから寄せて つかむ お手本を コード (rule_401) だけで 1 回録る.
推論のサーバーは使わない. run_rule401.py の流し方・止め方・記録の形をそのまま使う (import する. run_rule401.py は変えない).

1 回の流れ (run_rule401.py の 1〜7 と同じ. 違う所だけ):
  1. 割り振り plan_401.json を run_rule401.load_plan で確かめる + 依頼 406 の割り振り assign_406.json の --index 番の回
     (場所・置く向き・ずらし dx・dy・dyaw) を読む
  2. 机のカメラで読む (run_rule401.read_block). 目印の画素から R401_PIXEL_TOL_PX (既定 10) より離れていれば止める (置き直す).
     向きは 割り振りの向きと違っても止めない (読んだ向きで作る. trial.json に両方を残す). ただし 依頼 409: 割り振りの向きと
     読んだ向きの符号が逆で どちらも絶対値 REVERSE_MIN_DEG (6°) 以上なら 道を作る前に聞く (--execute のとき).
     r・Enter (yes でない) → 動かさずに止める (終了コード 3. 案内は同じ番号を置き直す). yes → 今までどおり進む
  3. 本当の道: 面の選び直し (--reselect-face) を常に入れた rule_401 の道とガード (run_rule401.build_choose).
     作れない・ガードに当たる → 動かさずに止める (終了コード 4. 案内は次の回へ進む. 飛ばした番号は <log>/rot406_skipped.jsonl)
  4. ずらした始めの道 (shift_406.build_shifted): うその読み (読んだ位置 + dx・dy mm, 向き + dyaw) の rule_401 の ブロックの上
     → 本当のブロックの上へ寄せる → 本当の道の下りる所から先 (1 コマも変えない). つないだ道に 3 と同じガード.
     うその読みで作れない・ガードに当たる → ずらし半分 → ずらし 0 (本当の道のまま)
  5〜7. run_rule401 と同じ (確かめ → HOME へ寄せる → 30fps で送りながら録る → 結果 → 記録). 確かめ・止める条件は足さない.
     台帳 <--log-dir>/so101_trials.csv に 1 行 (TRIAL_COLUMNS のまま. model = code_rule401_rot・step = rule_401・operator = code).
     試行のフォルダに rule401_plan.json (path = 送った道. true_path = 本当の rule_401 の道) と trial.json (rot406: 割り振りの番号・
     割り振りの向き・読んだ向き・使った dx・dy・dyaw・面の選び直し・ずらしたブロックの上の姿勢・keyframes)

ガードの値を変える口は run_rule401.py と同じ環境変数 (R401_PUSH_LIMIT_MM・R401_PUSH_WINDOW_MM・R401_PIXEL_TOL_PX・R401_START_TOL_DEG・
R401_ELEV_MAX_DEG・R401_CMD_FIRST). status を許すのは --allow-status (案内では R401_ALLOW_CONFLICT=1・R401_ALLOW_DEEP=1)

  P=/opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python
  $P so101/check_406/run_406.py --index 0 --dry-run --fake plan        (目印の画素・割り振りの向きを読んだことにする)
  $P so101/check_406/run_406.py --index 0 --log-dir /Volumes/KIOXIA/r2r2r-data/lab/so101_Log12 --execute
"""
import argparse
import json
import os
import sys
from datetime import datetime
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import shift_406 as SH  # noqa: E402

RR = SH.RR
R = RR.R
ASSIGN = HERE / "assign_406.json"
DRY_DIR = HERE / "dry_run"
SKIPPED = "rot406_skipped.jsonl"
EXIT_SKIP = 4                       # 本当の道が作れない (次の回へ)
REVERSE_MIN_DEG = 6.0               # 依頼 409: 割り振りと読んだ向きの符号が逆で どちらもこれ以上なら聞く (まっすぐの回は聞かない)


class TrueRefused(RR.Refused):
    """本当の道が作れない・ガードに当たる (その回を飛ばす)"""


def load_assign(path=ASSIGN, plan_path=RR.PLAN):
    a = json.loads(Path(path).read_text())
    if a.get("request") != 406 or len(a.get("trials", [])) != 60:
        raise RR.Refused(f"依頼 406 の割り振りではない: {path}")
    if a.get("plan_401_sha256") != RR.sha256(plan_path):
        raise RR.Refused("割り振りを作ったときの plan_401.json と 今の plan_401.json が違う")
    return a


def trial_of(assign, index):
    t = assign["trials"][int(index)]
    if t["index"] != int(index):
        raise RR.Refused(f"割り振りの番号が合わない: {index}")
    return t


def is_reverse(yaw_assign, yaw_read):
    """依頼 409: 割り振りの向きと読んだ向きの符号が逆で どちらも絶対値 REVERSE_MIN_DEG 以上"""
    a, r = float(yaw_assign), float(yaw_read)
    return abs(a) >= REVERSE_MIN_DEG and abs(r) >= REVERSE_MIN_DEG and (a > 0) != (r > 0)


def deg_text(v):
    t = f"{float(v):+.1f}"
    return (t[:-2] if t.endswith(".0") else t).replace("-", "−") + "°"


def ask_reverse(msg):
    """依頼 409: 逆向きのとき聞く. yes なら True (r・Enter・ほか・入力が閉じた → False)"""
    try:
        return input(f"\033[1;33m{msg}\033[0m 置き直すなら r、このまま流すなら yes > ").strip() == "yes"
    except EOFError:
        return False


def prepare(W, plan, assign, index, lo, hi, desk_rgb=None, fake=None, allow_status=(), ask=None):
    """読む → 本当の道 → ずらした始めの道. → (s, info). 止めるときは Refused (info は .info). 本当の道が作れないときは TrueRefused.
    ask (依頼 409): 逆向きのとき 道を作る前に呼ぶ (ask(文) → yes なら True). None なら聞かない (記録だけ)"""
    import yaw_lib_343 as Y
    t = trial_of(assign, index)
    place = int(t["place"])
    e = RR.episode_of(plan, place)
    uv, yaw_read, det = RR.read_block(W, desk_rgb, fake)
    yaw = round(float(Y.unwrap_near(yaw_read, float(e["yaw"]))), 1)
    d_px = float(np.linalg.norm(uv - np.asarray(e["pixel"])))
    info = {"place": place, "block_pixel": np.round(uv, 1).tolist(), "block_yaw_deg": yaw, "block_read": det,
            "plan_pixel": e["pixel"], "yaw_plan": float(e["yaw"]), "from_candidate": False, "pixel_from_plan_px": round(d_px, 1)}
    rot = {"index": int(t["index"]), "round": t["round"], "yaw_assign_deg": t["yaw_plan"], "yaw_read_deg": yaw,
           "yaw_read_minus_assign_deg": round(yaw - float(t["yaw_plan"]), 1),
           "shift_plan": {k: t[k] for k in ("dx", "dy", "dyaw", "shift_mm", "shift_dir_deg")}, "zero_plan": bool(t["zero"])}
    info["rot406"] = rot
    try:
        ptol = float(os.environ.get("R401_PIXEL_TOL_PX", RR.PIXEL_TOL_PX))
        if d_px > ptol:
            raise RR.Refused(f"ブロックが 場所{place} の目印から {info['pixel_from_plan_px']:.0f} 画素 離れている (許し {ptol:g} 画素). 置き直す")
        rot["reverse"] = is_reverse(t["yaw_plan"], yaw)
        if rot["reverse"] and ask is not None:
            msg = f"逆向きです（割り振り {deg_text(t['yaw_plan'])} ／ 読んだ向き {deg_text(yaw)}）。"
            rot["reverse_yes"] = bool(ask(msg))
            if not rot["reverse_yes"]:
                raise RR.Refused(f"{msg} yes でないので動かしません. 置き直す")
        jt = plan.get("jaw_table_min_mm")
        try:
            tb, meta = SH.build_true(W, e, uv, yaw, lo, hi, jt, allow_status)
        except RR.Refused as x:
            if getattr(x, "b", None) is not None:
                info.update(RR.summary(x.b))
            info.update(getattr(x, "info_extra", {}))
            raise TrueRefused(f"本当の道が作れない: {x}") from None
        info.update(RR.summary(tb))
        info.update(meta)
        s = SH.build_shifted(W, e, uv, yaw, lo, hi, jt, allow_status, (t["dx"], t["dy"], t["dyaw"]), true=(tb, meta))
    except RR.Refused as x:
        x.info = info
        raise
    # 送る道のすき間・ガード・予想 (ずらし 0 なら本当の道と同じ)
    info.update({"clearance_mm": s["clear"], "guards": s["guards"], "frames": len(s["path"]),
                 "keyframes": {k: int(v) for k, v in s["frames"].items()}, "pred": s["pred"],
                 "step_max_joint_deg": s["step_max"][0], "step_max_grip": s["step_max"][1]})
    rot.update({"shift_used": s["shift_used"], "scale": s["scale"], "halved": s["scale"] == 0.5,
                "to_zero": bool(s["scale"] == 0.0 and not t["zero"]), "bring_frames": s["bring_frames"],
                "bring": SH.bring_metrics(W, s), "tries": s["tries"], "fake": s["fake"],
                "above_shifted": None if s["above_shifted"] is None else np.round(s["above_shifted"], 3).tolist(),
                "keyframes": SH.keyframes(s["path"], s["frames"]), "true_frames": len(tb["path"]),
                "true_pred_grasp_jaw_table": tb["v"]["pred"]["grasp_jaw_table"]})
    return s, info


def plan_doc(s, info, plan_path):
    d = RR.plan_doc(s["b"], info, plan_path)          # 本当の道 (path・pred_path・rule351_path・keyframes_pose)
    d["request"] = 406
    d["what"] = ("依頼 406: ずらしたブロックの上 → 本当のブロックの上へ寄せる → rule_401 の道 (HOME → つかむ → 箱 → HOME). "
                 "path = 送った道. true_path = 本当の rule_401 の道 (下りる所から先は path と同じ)")
    d["true_path"], d["true_pred_path"] = d.pop("path"), d.pop("pred_path")
    d["path"] = np.round(np.asarray(s["path"]), 3).tolist()
    d["pred_path"] = np.round(np.asarray(s["pred_path"]), 3).tolist()
    d["assign_406_sha256"] = RR.sha256(ASSIGN) if ASSIGN.exists() else ""
    return d


def print_summary(info, ok, why):
    rot = info.get("rot406") or {}
    print(f"\033[1;36m[R406  ] {rot.get('index')} 番 (場所{info.get('place')}): 割り振りの向き {rot.get('yaw_assign_deg')}°・"
          f"読んだ向き {info.get('block_yaw_deg')}°\033[0m")
    if "shift_used" in rot:
        su = rot["shift_used"]
        how = {1.0: "割り振りのまま", 0.5: "半分にした", 0.0: "0 にした"}.get(rot["scale"], "")
        if rot.get("zero_plan"):
            how = "割り振りで 0"
        print(f"[R406  ] ずらし dx {su['dx']:+.1f}・dy {su['dy']:+.1f} mm・dyaw {su['dyaw']:+.1f}° ({how}). 寄せる {rot['bring_frames']} コマ")
    RR.print_summary(info, ok, why)


def write_skip(log_dir, index, why, stamp):
    with open(Path(log_dir) / SKIPPED, "a") as f:
        f.write(json.dumps({"index": int(index), "at": stamp, "why": why[:500]}, ensure_ascii=False) + "\n")


def parse_fake(s, plan, assign, index):
    if s is None:
        return None
    t = trial_of(assign, index)
    if s == "plan":
        e = RR.episode_of(plan, t["place"])
        return (float(e["pixel"][0]), float(e["pixel"][1]), float(t["yaw_plan"]))
    u, v, y = (float(x) for x in s.split(","))
    return (u, v, y)


def dry_run(args, plan, assign, lo, hi):
    W = RR.world()
    arm = None
    try:
        fake = parse_fake(args.fake, plan, assign, args.index)
        desk = None
        if fake is None:
            arm = R.DryArm()
            _, desk, _ = arm.observe()
        try:
            s, info = prepare(W, plan, assign, args.index, lo, hi, desk, fake, tuple(args.allow_status))
            ok, why, code = True, "", 0
        except RR.Refused as x:
            s, info, ok, why = None, getattr(x, "info", {}), False, str(x)
            code = EXIT_SKIP if isinstance(x, TrueRefused) else RR.EXIT_REFUSED
    finally:
        if arm is not None:
            arm.close()
    DRY_DIR.mkdir(parents=True, exist_ok=True)
    stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    name = f"dry_{args.index:02d}_{'fake' if fake is not None else 'cam'}_{stamp}.json"
    doc = dict(plan_doc(s, info, args.plan) if s is not None else {"request": 406, **info}, dry_run=True, fake=fake,
               would_send=ok, refused=why)
    (DRY_DIR / name).write_text(json.dumps(doc, ensure_ascii=False, default=str) + "\n")
    print_summary(info, ok, why)
    print(f"[DRY   ] {DRY_DIR / name}")
    return code


def execute(args, plan, assign, lo, hi):
    """run_rule401.execute と同じ流れ (道の作り方と記録の中身だけ違う)"""
    import lerobot_safe_259 as safe
    log_dir = Path(args.log_dir)
    bad = RR.kioxia_bad(log_dir)
    if bad:
        sys.exit(f"[ERROR] {bad}")
    W = RR.world()
    stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    trial = f"so101_{stamp}"
    local = R.LOCAL_RUNS / log_dir.name / trial
    local.parent.mkdir(parents=True, exist_ok=True)
    safe.check_dataset_root(local)
    if local.exists():
        sys.exit(f"[ERROR] ローカルの記録がもうある: {local}")
    current_motors = R.CURRENT_SETS[args.currents]
    arm, recorder, runner, s, info, err, result, reason = None, None, None, None, {}, "", "", ""
    held = False
    try:
        arm = R.LiveArm(current_motors)
        _, desk, _ = arm.observe()
        try:
            s, info = prepare(W, plan, assign, args.index, lo, hi, desk, None, tuple(args.allow_status), ask=ask_reverse)
        except RR.Refused as x:
            info = getattr(x, "info", {})
            print_summary(info, False, str(x))
            print(f"\n\033[1;37;41m   動かしません: {x}   \033[0m")
            if isinstance(x, TrueRefused):
                write_skip(log_dir, args.index, str(x), stamp)
                return EXIT_SKIP
            return RR.EXIT_REFUSED
        print_summary(info, True, "")
        path = np.asarray(s["path"], np.float64)
        st0, _, _ = arm.observe()
        d0 = float(np.abs(np.asarray(st0, np.float64)[:5] - path[0, :5]).max())
        tol0 = float(os.environ.get("R401_START_TOL_DEG", RR.START_TOL_DEG))
        if d0 > tol0:
            dj0 = np.round(np.asarray(st0, np.float64)[:5] - path[0, :5], 1).tolist()
            print(f"\n\033[1;37;41m   動かしません: 今の姿勢が HOME から {d0:.1f}° 離れている (許し {tol0:g}°. 関節ごとの差 {dj0})   \033[0m")
            return RR.EXIT_REFUSED
        loosened = [f"status {info.get('status')} (--allow-status)"] if info.get("status") != "ok" else []
        if loosened:                             # run_rule401 と同じ: 緩める口を使う回は 毎回 yes を打つ
            print(f"\033[1;33m[R401  ] この回は 決まりの外の口を使います: {' / '.join(loosened)}\033[0m")
            if input("流すなら yes と打つ > ").strip() != "yes":
                print("[R401  ] yes でないので動かしません")
                return RR.EXIT_REFUSED
        elif not args.skip_first_confirm:
            input("Enter で始める (Ctrl-C でやめる) > ")
        made = []

        def make_recorder():
            made.append(R.Recorder(local, f"local/{trial}", current_motors=current_motors, max_step=args.max_step_deg))
            return made[0]
        with R.KeyReader() as keys:
            keys.start()
            runner = RR.Runner(arm, make_recorder, keys, args.max_step_deg)
            try:
                runner.run(path, s["pred_path"])
            finally:
                recorder = made[0] if made else None
    except KeyboardInterrupt:
        err = "Ctrl-C"
        print("\n[STOP  ] Ctrl-C で止めました")
        held = True
        RR.safe_hold(arm)
    except RR.Refused as x:
        err = str(x)
        print(f"\n\033[1;37;41m   動かしません: {x}   \033[0m")
        held = True
        RR.safe_hold(arm)
    except Exception as x:
        err = f"{type(x).__name__}: {x}"
        print(f"\n[STOP  ] 失敗で止まりました: {err}")
        held = True
        RR.safe_hold(arm)
    finally:
        cleanup_err, close_failed = "", False
        try:
            if recorder is not None and recorder.n and runner is not None and runner.info.get("status") == "done":
                result = R.ask_result()
                reason = R.ask_fail_reason() if result == "failure" else ""
        except BaseException as x:
            result, reason = "", ""
            cleanup_err = f"結果を聞く間に {type(x).__name__}"
            print(f"\n[STOP  ] {cleanup_err}")
            if not held:
                held = True
                RR.safe_hold(arm)
        try:
            try:
                if recorder is not None:
                    recorder.close()
            except BaseException as x:
                cleanup_err = f"記録を閉じる間に {type(x).__name__}: {x}"
                err = err or cleanup_err
                recorder, close_failed = None, True
                print(f"\n[STOP  ] {cleanup_err}")
                if not held:
                    held = True
                    RR.safe_hold(arm)
        finally:
            if arm is not None:
                arm.close()
    if recorder is None or not recorder.n:
        if close_failed:
            print(f"[ERROR] 記録を閉じられない. ローカル {local} を見てください (台帳には書いていません)")
            return 1
        if RR.drop_empty_local(local, existed=False):
            print(f"[R406  ] 0 コマ目を記録する前に止まったので ローカルの空の記録を消しました: {local}")
        print(f"[R406  ] 道を送る前に止めたので 台帳に書きません ({err or (runner.info.get('stopped') if runner else '')})")
        return RR.EXIT_REFUSED if err else 0
    bad = RR.kioxia_bad(log_dir)
    if bad:
        print(f"[ERROR] {bad}. 記録はローカル {local} に残っています (台帳には書いていません)")
        return 1
    dst = log_dir / "so101" / trial
    dst.parent.mkdir(parents=True, exist_ok=True)
    n_files = R.copy_record(local, dst)
    modes = recorder.modes
    ri = runner.info if runner is not None else {}
    row = {"trial": trial, "started_at": stamp, "operator": SH.OPERATOR, "place": info["place"], "model": SH.MODEL_NAME,
           "step": SH.STEP_NAME, "exec_steps": "", "execute": 1, "result": result, "frames": len(modes),
           "frames_model": modes.count(R.MODEL), "frames_correct": modes.count(R.CORRECT), "frames_pause": modes.count(R.PAUSE),
           "queries": 0, "clipped_frames": ri.get("step_clipped_frames", 0), "record_dir": str(dst), "prefetch": "",
           "fail_reason": reason, "currents": args.currents, "play_speed": 1.0, "rtc": 0, "blend": 0, "max_step_deg": args.max_step_deg}
    R.append_trial(log_dir / R.TRIALS_CSV, row)
    (dst / RR.PLAN_FILE).write_text(json.dumps(plan_doc(s, info, args.plan), ensure_ascii=False, default=str) + "\n")
    (dst / "trial.json").write_text(json.dumps({**row, "assign_index": int(args.index), "rot406": info.get("rot406"),
                                                 "rule401": {k: v for k, v in info.items() if k != "rot406"}, "run": ri,
                                                 "stopped_by": err, "safe_range": {"lo": lo.tolist(), "hi": hi.tolist()}},
                                                ensure_ascii=False, indent=2, default=str) + "\n")
    print(f"[RECORD] {dst} ({n_files} ファイル) / 1 行 → {log_dir / R.TRIALS_CSV}")
    return 0


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--index", type=int, required=True, help="割り振りの番号 (0〜59)")
    ap.add_argument("--plan", default=str(RR.PLAN))
    ap.add_argument("--assign", default=str(ASSIGN))
    ap.add_argument("--log-dir", help="記録の置き場所 (KIOXIA の lab/<Log>). --execute のとき要る")
    g = ap.add_mutually_exclusive_group(required=True)
    g.add_argument("--execute", action="store_true", help="フォロワーに送る")
    g.add_argument("--dry-run", action="store_true", help="送らない. 道を check_406/dry_run/ に書く")
    ap.add_argument("--fake", default=None, help="--dry-run で カメラを開かず U,V,YAW か plan (目印の画素・割り振りの向き) を読んだことにする")
    ap.add_argument("--skip-first-confirm", action="store_true")
    ap.add_argument("--max-step-deg", type=float, default=R.MAX_STEP_DEG)
    ap.add_argument("--currents", choices=sorted(R.CURRENT_SETS), default="off")
    ap.add_argument("--allow-status", nargs="*", default=[], choices=["conflict", "deep_at_zero"])
    args = ap.parse_args(argv)
    if not 0 <= args.index < 60:
        ap.error("--index は 0〜59")
    if not 1.0 <= args.max_step_deg <= R.MAX_STEP_DEG:
        ap.error(f"--max-step-deg は 1〜{R.MAX_STEP_DEG:g}")
    if args.fake is not None and not args.dry_run:
        ap.error("--fake は --dry-run のときだけ")
    if args.execute and not args.log_dir:
        ap.error("--execute には --log-dir が要る")
    try:
        plan, lo, hi = RR.load_plan(args.plan)
        assign = load_assign(args.assign, args.plan)
    except RR.Refused as x:
        sys.exit(f"[ERROR] {x}")
    if args.dry_run:
        return dry_run(args, plan, assign, lo, hi)
    return execute(args, plan, assign, lo, hi)


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