#!/usr/bin/env python3
"""依頼 433 の確かめ 2・3 (アーム・サーバーなし. 偽のアーム・偽のサーバー. KIOXIA は読むだけ):

2. SO101_NO_STOP=1 で 外したあと HOME へ戻らずに渡し直すか (場所3・4. fake_run_405 の FakeArm と同じ形):
   (a) 上がった所で読めた / (b) 腕で隠れた / (c) 遠くへ飛んだ (12-02 174149 の上がった所の机の絵で読んだ画素 132.8, 357.5)
3. 12-02 の so101j の切り替え方式で止まった回 (台帳の sw_status が lift_refused・stopped・not_closed・retry_refused・missed_max・dropped)
   を 同じ入力で流す: 始めの読み (記録の画素・向き)・挟んだか (記録の判定)・閉じた姿勢 (記録の judge.hold)・推論の安全範囲 (記録)・
   上がった所の机の絵 (記録の動画の code_go_home の直前のコマ. 本物の read_block で読む)・持ち上げの許し (記録の lift_tol).
   偽のアームの wrist_flex は 99.38° で頭打ち (12-02 の実機の読み. 依頼 432). π0.5 の上限で止まった回は 偽のサーバーが
   10 回目の答え (約 10 秒) で閉じ, 挟む (記録に閉じた姿勢がないので 決めた形).
4. 依頼 432 の挟んだ 22 回: 持ち上げ〜戻る道を 腕の範囲に丸めたとき 爪の先 (手先) がねらいからどれだけずれるか (mm)

  SO101_VAR_ROLL_RANGE=-67,58 $P so101/check_433/fake_run_433.py   → fake_run_433.json・.md
"""
import csv
import glob
import json
import os
import sys
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
for p in (SO101, SO101 / "ideal_var", SO101 / "check_392", SO101 / "check_399", SO101 / "check_401", SO101 / "check_405",
          SO101 / "sim" / "look_400"):
    if str(p) not in sys.path:
        sys.path.insert(0, str(p))

ENV = {"SO101_NO_STOP": "1", "R401_PIXEL_TOL_PX": "40"}      # session_433.sh と同じ (場所5 の R401_PICK は回ごとに)
os.environ.update(ENV)

import fake_run_405 as F5  # noqa: E402
import nostop_433 as NS  # noqa: E402
import run_so101_policy as R  # noqa: E402
import switch_405 as SW  # noqa: E402

LOG = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log12")
OUT = Path("/tmp/r433_dry")
WF_CAP = 99.38                       # 12-02 の実機の wrist_flex の頭打ち (依頼 432)
STOPPED = ("lift_refused", "stopped", "not_closed", "retry_refused", "missed_max", "dropped")
CLOSE_AFTER = 10                     # 上限で止まった回: この回数目の答えで閉じる


class Arm(F5.FakeArm):
    """FakeArm + wrist_flex の頭打ち + 上がったあとの机の絵 (rise_img) を返す"""

    def __init__(self, images, scene, sw, rise_img=None):
        super().__init__(images, scene)
        self.sw, self.rise_img = sw, rise_img

    def observe(self):
        st, desk, wrist = super().observe()
        if self.rise_img is not None and any(s["name"] == "code_open_rise" for s in self.sw.info["segments"]):
            desk = self.rise_img
        return st, desk, wrist

    def send(self, target):
        t = super().send(target)
        self.state[3] = min(self.state[3], WF_CAP)
        return t


class Client(F5.FakeClient):
    """渡す所から 記録の閉じた姿勢 (holds[回]) か rule_401 のつかむ所 へ 1 コマ 1.5° で寄せて閉じる.
    外す回 (grips が False) で holds がなければ fake_run_405 と同じに 奥へ 15 mm ずらす. close_after[回] があれば その回数目の答えまで閉じない"""

    def __init__(self, sw, scene, arm):
        super().__init__(sw, scene, arm, latency=0.0)
        self.k_att, self.n_att = None, 0

    def infer(self, obs):
        att = len(self.sw.info["attempts"]) - 1
        if att != self.k_att:
            self.k_att, self.n_att = att, 0
        self.n_att += 1
        holds = self.scene.get("holds") or []
        if att < len(holds) and holds[att] is not None:
            s = np.asarray(obs["observation/state"], np.float64)
            goal = np.asarray(holds[att], np.float64)
        else:
            return self._base(obs, att)
        wait = (self.scene.get("close_after") or {}).get(att, 0)
        out, q = [], s.copy()
        for _ in range(30):
            q[:5] += np.clip(goal[:5] - q[:5], -1.5, 1.5)
            q[5] = 0.0 if (np.abs(goal[:5] - q[:5]).max() < 0.5 and self.n_att >= wait) else 59.0
            out.append(q.copy())
        return {"actions": np.asarray(out, np.float32)}

    def _base(self, obs, att):
        wait = (self.scene.get("close_after") or {}).get(att, 0)
        r = F5.FakeClient.infer(self, obs)
        if self.n_att < wait:
            r["actions"][:, 5] = 59.0
        return r


def video_frame(trial, which):
    import av
    d = LOG / "so101" / trial
    s = json.loads((d / "trial.json").read_text())["switch405"]
    seg = {x["name"]: x["start_frame"] for x in s["segments"]}
    if which not in seg:
        return None
    f = [x for x in glob.glob(str(d / "videos/observation.images.desk/**/*.mp4"), recursive=True) if "/._" not in x][0]
    want = seg[which] - 1
    for i, fr in enumerate(av.open(f).decode(video=0)):
        if i == want:
            return fr.to_ndarray(format="rgb24")
    return None


def run_one(name, place, scene, plan, lo, hi, W, plo, phi, lift_tol=None, pick=""):
    import argparse
    if pick:
        os.environ["R401_PICK"] = pick
    else:
        os.environ.pop("R401_PICK", None)
    SW.LIFT_POS_TOL_MM = float(lift_tol or 1.0)
    a = argparse.Namespace(port=8000, raw_dir=str(F5.RAW_H), log_dir=str(OUT / "log"), model="fake_433", step="0", exec_steps=30,
                           no_prefetch=False, skip_first_confirm=True, execute=False, place=place, currents="off", play_speed=1.0,
                           rtc=False, rtc_max_delay=None, blend=10, max_step_deg=5.0, switch_405=True, policy_max_s=None,
                           chunk_full=False, black_wrist=False, retry_shift_mm=None, allow_status=["conflict", "deep_at_zero"],
                           reselect_face=True, place1_candidate=False, retry_rise_first=True)
    clk = F5.Clock()
    sw = SW.Switch(a, plo, phi, W=W, plan=(plan, lo, hi), clock=clk, sleep=clk.sleep)
    sw.fake_reads = list(scene["reads"])
    import fake_run_392 as F
    arm = Arm(F.first_frames(place), scene, sw, scene.get("rise_img"))
    pol = R.Policy(0, client=Client(sw, scene, arm))
    rc = SW.execute(a, arm_factory=lambda: arm, policy=pol, keys=F5.Keys(sw, None), inp=lambda q="": "y", switch=sw,
                    local_root=OUT / "runs", kioxia_check=False)
    i = sw.info
    segs = [s["name"] for s in i["segments"]]
    home_mid = [k for k, s in enumerate(segs) if s == "code_go_home" and k != len(segs) - 1]
    ns = NS.summary()
    return {"name": name, "place": place, "status": i["status"], "rc": rc, "attempts": len(i["attempts"]),
            "judges": [(x.get("judge") or {}).get("class") for x in i["attempts"]], "routes": [x.get("route") for x in i["attempts"]],
            "segments": segs, "home_in_middle": bool(home_mid), "stop_where": i["stop_where"], "stop_why": i["stop_why"][:200],
            "rereads": [(x.get("reread") or {}).get("info") for x in i["attempts"]],
            "clips": {k: x.get(k) for x in i["attempts"] for k in ("after_path_clip", "open_rise_clip", "connect_clip", "go_home_clip") if x.get(k)},
            "nostop_n": ns["n"], "nostop_names": ns["names"], "nostop": [e["msg"] for e in ns["notes"]], "sent": arm.n_sent}


def main():
    import run_rule401 as RR
    OUT.mkdir(parents=True, exist_ok=True)
    (OUT / "log").mkdir(exist_ok=True)
    plan, lo, hi = RR.load_plan(RR.PLAN)
    W = RR.world()
    plo, phi, _ = R.load_safe_range(F5.RAW_H)
    doc = {"env": ENV, "wf_cap": WF_CAP, "shapes": [], "replays": [], "clip_mm": []}

    # 2. (a)(b)(c)
    for place in (3, 4):
        e = plan["episodes"][place - 1]
        mk = (float(e["pixel"][0]), float(e["pixel"][1]), 0.0)
        far = (132.8, 357.5, 13.5)
        for nm, reads in (("(a) 上がった所で読めた", [mk, mk]), ("(b) 腕で隠れた", [mk, "hidden"]),
                          ("(c) 遠くへ飛んだ (174149 の画素)", [mk, far])):
            sc = {"grips": [False, True], "reads": reads}
            print(f"\n===== 場所{place} {nm} =====", flush=True)
            doc["shapes"].append(run_one(nm, place, sc, plan, lo, hi, W, plo, phi))
            print(json.dumps({k: doc["shapes"][-1][k] for k in ("status", "routes", "home_in_middle", "nostop_names")}, ensure_ascii=False))

    # 3. 12-02 の so101j の止まった回
    with open(LOG / "so101_trials.csv", newline="") as f:
        rows = [r for r in list(csv.reader(f))[1:] if len(r) > 4 and r[4].startswith("so101j")]
    for r in rows:
        t = r[0]
        d = json.loads((LOG / "so101" / t / "trial.json").read_text())
        s = d["switch405"]
        if s["status"] not in STOPPED:
            continue
        att = s["attempts"]
        grips, holds, close_after = [], [], {}
        for k, x in enumerate(att):
            j = x.get("judge") or {}
            if j:
                grips.append(j["class"] == "held")
                holds.append(j["hold"])
            else:                                   # 上限で止まった回: 閉じた姿勢がない → rule_401 のつかむ所で 10 回目の答えで閉じて挟む
                grips.append(True)
                holds.append(None)
                close_after[k] = CLOSE_AFTER
        if all(g is False for g in grips):          # 外して止まった回: 次の回は rule_401 のつかむ所で挟む (決めた形)
            grips.append(True)
            holds.append(None)
        f0 = s["first"]
        reads = [(float(f0["block_pixel"][0]), float(f0["block_pixel"][1]), float(f0["block_yaw_deg"]))] + [None] * 4
        rise = video_frame(t, "code_go_home") if any("open_rise" in x for x in att) else None
        sc = {"grips": grips, "holds": holds, "reads": reads, "close_after": close_after, "rise_img": rise}
        lt = (s.get("lift_tol") or {}).get("pos_mm")
        print(f"\n===== {t} 場所{d['place']} 記録 {s['status']} =====", flush=True)
        safe = d["safe_range"]
        x = run_one(t, int(d["place"]), sc, plan, lo, hi, W, np.asarray(safe["lo"]), np.asarray(safe["hi"]), lt,
                    "min_elev" if str(d["place"]) == "5" else "")
        x.update(recorded_status=s["status"], recorded_where=s["stop_where"], recorded_why=s["stop_why"][:160], lift_tol=lt,
                 assumed=("上限で止まった回は 10 回目の答えで閉じて挟む形" if close_after else "") +
                 ("・外したあとは rule_401 のつかむ所で挟む形" if all(g is False for g in grips[:-1]) and len(grips) > len(att) else ""))
        doc["replays"].append(x)
        print(json.dumps({k: x[k] for k in ("status", "routes", "home_in_middle", "nostop_names")}, ensure_ascii=False))

    # 4. 丸めたときの爪の先のずれ
    doc["clip_mm"] = clip_table(W, rows)
    (HERE / "fake_run_433.json").write_text(json.dumps(doc, ensure_ascii=False, indent=1, default=SW._js) + "\n")
    write_md(doc)
    ok = all(x["status"] == "carried" and not x["home_in_middle"] for x in doc["shapes"])
    ok &= all(x["status"] not in ("lift_refused", "not_closed", "retry_refused") or x["status"] == "retry_refused" and "道が作れない" in x["stop_why"]
              for x in doc["replays"])
    return 0 if ok else 1


def clip_table(W, rows):
    import var_lib_314 as V
    alo, ahi = NS.arm_range()
    out = []
    for r in rows:
        t = r[0]
        s = json.loads((LOG / "so101" / t / "trial.json").read_text())["switch405"]
        for a in s["attempts"]:
            j = a.get("judge") or {}
            if j.get("class") != "held":
                continue
            path, fr, inf = SW.after_held_path(W.w.chain, np.asarray(j["hold"][:5], np.float64))
            c, cl = NS.clip_arm(path, alo, ahi)
            cap = path.copy()
            cap[:, 3] = np.minimum(cap[:, 3], WF_CAP)

            def err(p2, a0=fr["LIFT"], a1=fr["ABOVE_BOX"]):
                d = [float(np.linalg.norm(V.tcp_mm(W.w.chain, p2[i, :5]) - V.tcp_mm(W.w.chain, path[i, :5]))) for i in range(len(path))]
                return round(max(d), 1), round(d[fr["LIFT"]], 1), round(max(d[a0:a1 + 1]), 1)
            e_arm, e_cap = err(c), err(cap)
            out.append({"trial": t, "place": json.loads((LOG / "so101" / t / "trial.json").read_text())["place"], "attempt": a["attempt"],
                        "status": s["status"], "wf_max": round(float(path[:, 3].max()), 2), "wf_lift": round(float(path[fr["LIFT"], 3]), 2),
                        "clip": cl, "err_arm_max_mm": e_arm[0], "err_arm_lift_mm": e_arm[1], "err_arm_carry_max_mm": e_arm[2],
                        "err_cap_max_mm": e_cap[0], "err_cap_lift_mm": e_cap[1], "err_cap_carry_max_mm": e_cap[2]})
    return out


def write_md(doc):
    L = ["# 依頼 433: SO101_NO_STOP=1 の偽の通し (fake_run_433.py が書いた. アーム・サーバーなし)", "",
         f"環境変数 {doc['env']}・R401_RESELECT・SW405_RISE_FIRST・conflict と deep_at_zero を許す (session_433.sh と同じ). "
         f"偽のアームの wrist_flex は {doc['wf_cap']}° で頭打ち", "",
         "## 外したあと HOME へ戻らずに渡し直す (2 回目で挟む形)", "",
         "| 場所 | 形 | 結果 | 道すじ | 途中で HOME へ | 読み直し | 通り越した確かめ |", "|---|---|---|---|---|---|---|"]
    for x in doc["shapes"]:
        rr = [y for y in x["rereads"] if y]
        L.append(f"| {x['place']} | {x['name']} | {x['status']} | {x['routes']} | {'あり' if x['home_in_middle'] else 'なし'} | "
                 f"{rr[0].get('block_pixel') if rr else '-'} (目印から {rr[0].get('pixel_from_plan_px') if rr else '-'} 画素) | "
                 f"{x['nostop_n']}: {', '.join(x['nostop_names']) or '-'} |")
    L += ["", "## 12-02 の so101j で止まった回を 同じ入力で", "",
          "| 試行 | 場所 | 記録 (止まった所・理由) | NO_STOP の結果 | 渡した回・判定・道すじ | 決めた形 | 通り越した確かめ (名前と値) |",
          "|---|---|---|---|---|---|---|"]
    for x in doc["replays"]:
        L.append(f"| {x['name'][-6:]} | {x['place']} | {x['recorded_status']} ({x['recorded_where']}: {x['recorded_why'][:80]}) | "
                 f"{x['status']}{(' (' + x['stop_why'][:80] + ')') if x['stop_why'] else ''} | {x['attempts']}・{x['judges']}・{x['routes']} | "
                 f"{x['assumed'] or '-'} | {'<br>'.join(m[:150] for m in x['nostop']) or '-'} |")
    L += ["", "## 持ち上げ〜戻る道を腕の範囲に丸めたときの爪の先のずれ (依頼 432 の挟んだ回)", "",
          "腕の範囲 = 12-01 に手で測った値 (wrist_flex の上限 100.53°). 頭打ち = 実機の 99.38° に丸めたとき. ずれ = 丸めた道と丸める前の道の手先 (URDF) の距離",
          "", "| 試行 | 場所 | 回 | 結果 (記録) | wrist_flex 最大・持ち上げ | 丸め (腕の範囲) | ずれ 最大・持ち上げ・運ぶ間 (mm) | 頭打ち 99.38° のずれ (mm) |",
          "|---|---|---|---|---|---|---|---|"]
    for x in doc["clip_mm"]:
        cl = ", ".join(f"{k} {v['clip_deg']:+.2f}°" for k, v in x["clip"].items()) or "なし"
        L.append(f"| {x['trial'][-6:]} | {x['place']} | {x['attempt']} | {x['status']} | {x['wf_max']}・{x['wf_lift']} | {cl} | "
                 f"{x['err_arm_max_mm']}・{x['err_arm_lift_mm']}・{x['err_arm_carry_max_mm']} | "
                 f"{x['err_cap_max_mm']}・{x['err_cap_lift_mm']}・{x['err_cap_carry_max_mm']} |")
    (HERE / "fake_run_433.md").write_text("\n".join(L) + "\n")
    print("\n".join(L))


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