"""依頼 433: 切り替え方式 (コード → π0.5 → コード) で「止める確かめ」を「知らせるだけ」に変える口 (SO101_NO_STOP=1 のときだけ).

付けなければ何もしない (on() が False. 呼ぶ側は今と 1 コマも変わらない).
付けたとき:
  - note(name, msg, **値): 止めずに 1 行 [NOSTOP] 〜だが流す を出し, 通り越した確かめとして残す (trial.json の switch405.nostop)
  - relaxed(): rule_401 の道を作る所 (run_rule401.prepare) が 今までどおりでは作れない・ガードに当たったときだけ入る 2 段目.
      この間は make_path・lib_399.variant・face_349.try_path・build のガードなどが 止めずに soft() に理由を残し, いちばん近い答えで進める.
      soft() は 候補ごとの理由を ためるだけ (出さない). 選んだ道の分だけ 呼ぶ側が note() で出す (候補を試すたびに出すと 何十行にもなるため)
  - clip_arm(path, ...): 腕の範囲 (12-01 に手で測った var_lib_314.arm_range) の外の値を その端に丸め, 関節ごとの丸めた度を返す
2026-12-02 17:59 エイイチ:「危険でもなんでもないから止めるの全解除してほしい」. 止めてよいのは スペース・q と 計算ができないときだけ
"""
import os
from contextlib import contextmanager

import numpy as np

ENV = "SO101_NO_STOP"
_log = []          # 通り越した確かめ (出したもの)
_soft = []         # relaxed の間に ためた理由 (候補ごと. 出さない)
_relax = [0]
_out = [print]
_once = set()


def on():
    return os.environ.get(ENV, "").strip() == "1"


def set_out(f):
    _out[0] = f


def reset():
    _log.clear()
    _soft.clear()
    _once.clear()
    _relax[0] = 0


def _js(v):
    if isinstance(v, np.ndarray):
        return np.round(v.astype(np.float64), 3).tolist()
    if isinstance(v, (np.floating, np.integer)):
        return round(float(v), 3)
    if isinstance(v, float):
        return round(v, 3)
    return v


def note(name, msg, once_key=None, **vals):
    """止めずに知らせる. → 残した記録 (dict). once_key を渡せば 同じ鍵は 2 度目から出さず 前の記録を返す (値の最大は呼ぶ側で直す)"""
    if once_key is not None:
        for e in _log:
            if e.get("once_key") == once_key:
                return e
    e = {"name": name, "msg": msg, **{k: _js(v) for k, v in vals.items()}}
    if once_key is not None:
        e["once_key"] = once_key
    _log.append(e)
    _out[0](f"\033[1;35m[NOSTOP] {msg}だが流す\033[0m")
    return e


def log():
    return list(_log)


def summary():
    names = []
    for e in _log:
        if e["name"] not in names:
            names.append(e["name"])
    return {"on": on(), "n": len(_log), "names": names, "notes": [{k: v for k, v in e.items() if k != "once_key"} for e in _log]}


# ---- 2 段目 (relaxed) ----------------------------------------------------------------------------

def relaxed_on(range_too=False):
    """2 段目か. range_too: 範囲・1 コマの確かめも緩める段 (2) か. 2 段目は まず範囲・1 コマは今のまま (1) で選び,
    それでも作れないときだけ 全部を緩める (2). 範囲の外は丸めるので 道が大きく変わる候補を先に選ばないため"""
    return _relax[0] >= (2 if range_too else 1)


@contextmanager
def relaxed(level=1):
    old = _relax[0]
    _relax[0] = max(old, int(level))
    try:
        yield
    finally:
        _relax[0] = old


def soft(name, msg, **vals):
    """relaxed の間: 止めずに理由をためる (出さない). → True"""
    _soft.append({"name": name, "msg": msg, **{k: _js(v) for k, v in vals.items()}})
    return True


def mark():
    return len(_soft)


def since(m):
    return list(_soft[m:])


# ---- 腕の範囲に丸める ----------------------------------------------------------------------------

def arm_range():
    import var_lib_314 as V
    lo, hi = V.arm_range()
    return np.asarray(lo, np.float64), np.asarray(hi, np.float64)


def clip_arm(path, lo=None, hi=None, motors=None):
    """→ (丸めた道, {関節: 丸めた最大の度 (符号つき. − = 上の端へ下げた)}). 丸めがなければ {} と同じ道"""
    if lo is None:
        lo, hi = arm_range()
    p = np.asarray(path, np.float64)
    c = np.clip(p, lo, hi)
    d = c - p
    out = {}
    if motors is None:
        import run_so101_policy as R
        motors = R.MOTORS
    for j in np.where(np.abs(d).max(0) > 1e-9)[0]:
        k = int(np.argmax(np.abs(d[:, j])))
        out[motors[j]] = {"clip_deg": round(float(d[k, j]), 3), "want": round(float(p[k, j]), 3),
                          "edge": round(float(lo[j] if d[k, j] > 0 else hi[j]), 3), "frames": int((np.abs(d[:, j]) > 1e-9).sum())}
    return c, out


def path_notes(where, path, rlo, rhi, step_deg=10.0, step_grip=20.0, motors=None):
    """道を作る範囲 (お手本の幅) の外・1 コマの変化の上限 を知らせる (止めない). 腕の範囲の外は clip_arm で丸める.
    → (送る道, 丸めの記録)"""
    if motors is None:
        import run_so101_policy as R
        motors = R.MOTORS
    p = np.asarray(path, np.float64)
    out_r = np.where(((p < rlo - 1e-9) | (p > rhi + 1e-9)).any(0))[0]
    for j in out_r:
        lo_x, hi_x = float(p[:, j].min()), float(p[:, j].max())
        note("rule_range", f"{where}: {motors[j]} が道を作る範囲 (お手本の幅 {float(rlo[j]):.1f}〜{float(rhi[j]):.1f}) の外 "
             f"({lo_x:.1f}〜{hi_x:.1f})", where=where, joint=motors[j], min=lo_x, max=hi_x, lo=float(rlo[j]), hi=float(rhi[j]))
    if len(p) > 1:
        d = np.abs(np.diff(p, axis=0))
        sj, sg = float(d[:, :5].max()), float(d[:, 5].max())
        if sj > step_deg + 1e-9 or sg > step_grip + 1e-9:
            note("step", f"{where}: 1 コマの変化 関節 {sj:.2f}°・爪 {sg:.2f} (上限 {step_deg:g}°・{step_grip:g}. 丸めない)",
                 where=where, step_joint=sj, step_grip=sg)
    c, cl = clip_arm(p, motors=motors)
    for m, v in cl.items():
        note("arm_range_clip", f"{where}: {m} {v['want']:.2f}° が腕の範囲 (12-01 に測った) の外 (端 {v['edge']:.2f}° に丸める "
             f"{v['clip_deg']:+.2f}°・{v['frames']} コマ)", where=where, joint=m, **v)
    return c, cl
