"""依頼 395 のテスト (アーム・カメラ・サーバーにはつながない).

- --first-chunk-only: 場所2〜5 で 渡す所まで動かし, 推論に 1 回だけ問い合わせ, 最初の答えは **1 コマも送らない**.
  問い合わせのあとの送りは 来たコードの道を逆にした値だけ (1 コマ 5° で切ったもの). 台帳は 1 行 (結果は空・first_only)・
  試行のフォルダに first_chunk_395.json (記録の値つき)
- 沈み (遅れのある腕)・戻る道でスペース・問い合わせの失敗・引数の組み合わせ・(a) で流したら送った値の計算
- report_395.py (表・判定の案・図)・report_394.py の E5 の列・session_395.sh の回し方

  /opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python -m unittest so101/check_395/test_first_chunk_395.py -v
"""
import csv
import json
import subprocess
import sys
import tempfile
import unittest
import unittest.mock
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
SO101 = HERE.parent
for p in (SO101, SO101 / "check_392", SO101 / "check_394", HERE):
    sys.path.insert(0, str(p))
import run_so101_policy as R  # noqa: E402

PLAN = SO101 / "check_394" / "plan_394.json"
CALIB = Path("/Volumes/KIOXIA/r2r2r-data/lab/so101_Log12/315/calib_points_315.json")
RAW_G = Path("/Volumes/KIOXIA/r2r2r-data/datasets/so101_redblock_box_ideal_var_v2_success_recover_v1/raw_episodes")
HAVE_KIOXIA = CALIB.exists() and RAW_G.exists()
COLS = R.TRIAL_COLUMNS + R.HANDOVER_COLUMNS + R.FIRST_CHUNK_COLUMNS


class Client:
    """答え: 今の角度から 肩を 1 コマ 1° ずつ下げ 肘を 1° ずつ伸ばす (目立つ値). 問い合わせた時の 送った数 を覚える"""

    def __init__(self, counter, arm_ref, fail=False):
        self.counter, self.arm_ref, self.fail = counter, arm_ref, fail

    def infer(self, obs):
        self.counter["queries"] += 1
        self.counter["sent_at_query"] = len(self.arm_ref[0].sent)
        if self.fail:
            raise ConnectionError("偽のサーバーの失敗")
        s = np.asarray(obs["observation/state"], np.float64)
        d = np.zeros(6)
        d[1], d[2] = 1.0, -1.0
        return {"actions": np.stack([s + d * (k + 1) for k in range(30)]).astype(np.float32)}

    def close(self):
        pass


@unittest.skipUnless(HAVE_KIOXIA, "KIOXIA (校正の点・so101g の学習データ) がない")
class TestFirstChunk(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        import handover_392 as H
        import test_handover_392 as T
        cls.H, cls.T = H, T
        cls.plan = json.loads(PLAN.read_text())

    def trial(self, place, keys_at=None, lag=None, fail=False, extra=()):
        import lerobot_safe_259 as safe
        H, T = self.H, self.T
        e = self.plan["episodes"][place - 1]
        orig_read = H.Handover.read
        d = Path(tempfile.mkdtemp())
        log = d / "log"
        log.mkdir()
        counter = {"queries": 0}
        arm = T.Arm([safe.load_rest_pose()[0][m] for m in R.MOTORS], lag=lag)
        asked = []
        with unittest.mock.patch.object(H.Handover, "read",
                                        lambda self, desk, fake=None: orig_read(self, desk, (e["pixel"][0], e["pixel"][1], 0.0))), \
                unittest.mock.patch.object(R, "ask_result", lambda inp=None: asked.append(1) or "success"), \
                unittest.mock.patch.object(R, "DryArm", lambda: arm), \
                unittest.mock.patch.object(R, "Policy", lambda port, _b=R.Policy: _b(port, client=Client(counter, [arm], fail))), \
                unittest.mock.patch.object(R, "KeyReader", lambda: T.Keys(counter, 10 ** 6, keys_at)), \
                unittest.mock.patch.object(R, "LOCAL_RUNS", d / "runs"), \
                unittest.mock.patch.object(R, "ask_fail_reason", lambda inp=None: ""), \
                unittest.mock.patch("builtins.input", lambda p="": ""):
            rc = R.main(["--log-dir", str(log), "--place", str(place), "--raw-dir", str(RAW_G), "--model", "so101g",
                         "--exec-steps", "30", "--blend", "10", "--max-step-deg", "5", "--handover-above-mm", "50",
                         "--handover-plan", str(PLAN), "--first-chunk-only", *extra])
        with open(log / R.TRIALS_CSV) as f:
            rows = list(csv.reader(f))
        row = dict(zip(COLS, rows[1]))
        doc_p = Path(row["record_dir"]) / "first_chunk_395.json"
        doc = json.loads(doc_p.read_text()) if doc_p.exists() else None
        return rc, rows, row, arm, asked, counter, doc

    def expected_back(self, code, start):
        """来たコードの道を逆に 1 コマ 5° で切って送った値"""
        out, last = [], np.asarray(start, np.float64)
        for t in code[::-1]:
            s, _ = R.step_clip(t, last, 5.0)
            out.append(s)
            last = s
        return np.asarray(out)

    def test_not_sent_2_to_5(self):
        for place in (2, 3, 4, 5):
            with self.subTest(place=place):
                rc, rows, row, arm, asked, counter, doc = self.trial(place)
                self.assertEqual(rc, 0)
                self.assertEqual(rows[0], COLS)                    # 新しい台帳なので見出しは 3 つを合わせた列
                self.assertEqual((row["handover_status"], row["result"], row["first_chunk_only"], row["frames_model"]),
                                 ("first_only", "", "1", "0"))
                self.assertEqual(asked, [])                        # 結果は聞かない
                self.assertEqual(counter["queries"], 1)            # 1 回だけ問い合わせる
                n0 = counter["sent_at_query"]
                after = np.asarray(arm.sent[n0:])
                code = np.asarray(doc["chunk_target"])
                plan = json.loads((Path(row["record_dir"]) / "handover_plan_392.json").read_text())
                path = np.asarray(plan["code_path"])
                # 問い合わせのあとの送りは 来た道を逆にしたものだけ (最初の答えのコマは 1 つもない)
                # (記録の道は 3 桁に丸めてある. 丸めの差 5e-4 の分だけ許す)
                np.testing.assert_allclose(after, self.expected_back(path, arm.sent[n0 - 1]), atol=2e-3)
                self.assertEqual(len(after), len(path))
                np.testing.assert_allclose(after[-1], path[0], atol=1e-3)          # HOME で終わる
                for t in code:                                    # 答えの目標は どの送りとも違う (肩 +1°/コマ で離れていく)
                    self.assertGreater(np.abs(after[:, :5] - t[:5]).max(1).min(), 0.5)
                self.assertEqual(doc["sent_chunk_frames"], 0)
                self.assertEqual(len(doc["chunk_raw"]), 30)
                self.assertFalse(doc["return_stopped"])
                an = doc["analysis"]
                self.assertAlmostEqual(an["jump"]["joint_max_deg"], 1.0, places=3)
                self.assertEqual(an["cut"]["frames"], 0)          # 1 コマ 1° なので 5° では切られない
                self.assertEqual(an["sink"]["joint_max_deg"], 0.0)
                self.assertEqual(int(row["frames"]), int(row["frames_code"]) + int(row["frames_wait"]))   # 記録は道と待ちだけ
                self.assertEqual(row["first_cut_frames"], "0")

    def test_sink_lagging_arm(self):                # 遅れのある腕: 沈み (指令 − 実際) が出る
        rc, rows, row, arm, asked, counter, doc = self.trial(4, lag=0.5)
        self.assertEqual(row["handover_status"], "first_only")
        s = doc["analysis"]["sink"]
        self.assertGreater(s["joint_max_deg"], 0.0)
        np.testing.assert_allclose(np.asarray(doc["state_at_query"]) - np.asarray(doc["handover_cmd"]), s["joint_deg"], atol=1e-3)
        self.assertGreater(float(row["sink_tcp_mm"]), 0.0)

    def test_stop_on_return(self):                  # 戻る道の途中でスペース → その場で止める
        T = self.T
        polls = {"n": 0}
        Base = T.Keys

        class K(Base):
            def poll(self):
                if self.counter["queries"] == 0:
                    return Base.poll(self)
                polls["n"] += 1
                return " " if polls["n"] == 10 else None
        with unittest.mock.patch.object(T, "Keys", lambda c, n, at=None: K(c, n, at)):
            rc, rows, row, arm, asked, counter, doc = self.trial(3)
        self.assertEqual(row["handover_status"], "first_return_stopped")       # codex R1 C2: 数えない
        self.assertEqual(row["result"], "")
        self.assertTrue(doc["return_stopped"])
        self.assertEqual(doc["return_frames"], 9)
        self.assertEqual(len(arm.sent) - counter["sent_at_query"], 10)    # 9 コマ + その場で止める 1 回

    def test_return_tracking_recorded(self):        # codex R1 C2: 戻り始めの差・追従の差・HOME との差を記録する
        rc, rows, row, arm, asked, counter, doc = self.trial(2, lag=0.5)
        self.assertEqual(row["handover_status"], "first_only")
        self.assertGreater(doc["return_start_diff_deg"], 0.0)
        self.assertGreater(doc["return_track_max_deg"], 0.0)
        self.assertIsNotNone(doc["return_home_diff_deg"])

    def test_plan_fail_returns(self):               # codex R1 C2: 問い合わせのあとの計算の失敗も 来た道で戻す
        with unittest.mock.patch.object(R, "plan_chunk", side_effect=ValueError("偽の失敗")):
            rc, rows, row, arm, asked, counter, doc = self.trial(4)
        self.assertEqual(row["handover_status"], "first_failed")
        n0 = counter["sent_at_query"]
        plan = json.loads((Path(row["record_dir"]) / "handover_plan_392.json").read_text())
        self.assertEqual(len(arm.sent) - n0, len(plan["code_path"]))

    def test_query_fail_returns(self):              # 問い合わせの失敗: 来た道で戻してから止める. 結果は聞かない
        rc, rows, row, arm, asked, counter, doc = self.trial(5, fail=True)
        self.assertEqual(row["handover_status"], "first_failed")
        self.assertEqual(row["result"], "")
        self.assertEqual(asked, [])
        self.assertIsNone(doc)
        n0 = counter["sent_at_query"]
        plan = json.loads((Path(row["record_dir"]) / "handover_plan_392.json").read_text())
        np.testing.assert_allclose(np.asarray(arm.sent[n0:]), self.expected_back(np.asarray(plan["code_path"]), arm.sent[n0 - 1]),
                                   atol=2e-3)


class TestUnits(unittest.TestCase):
    def test_args(self):
        with self.assertRaises(SystemExit):
            R.main(["--log-dir", "/tmp", "--first-chunk-only"])          # --handover-above-mm なしは受けない

    def test_simulate_send(self):
        import first_chunk_395 as FC
        start = np.zeros(6)
        tg = np.array([[7.0, 0, 0, 0, 0, 30.0], [8.0, 0, 0, 0, 0, 30.0], [8.0, 0, 0, 0, 0, 30.0]])
        s, cut = FC.simulate_send(tg, start, 5.0)
        np.testing.assert_allclose(s[:, 0], [5.0, 8.0, 8.0])
        np.testing.assert_allclose(s[:, 5], [20.0, 30.0, 30.0])           # 爪は入口の B の 20
        self.assertEqual(cut, [0])

    def test_default_columns_unchanged(self):
        self.assertEqual(R.TRIAL_COLUMNS[-1], "max_step_deg")
        self.assertEqual(R.HANDOVER_COLUMNS[-1], "code_plan")


def fake_analysis(jump=1.0, tcp=3.0, cut=0, toward=0.8, h0=10.0, h1=6.0, gmin=35.0, table=40.0, late=None):
    return {"sink": {"joint_max_deg": 0.5, "tcp_mm": 2.0, "tcp_z_mm": -1.5},
            "jump": {"joint_max_deg": jump, "joint_max_name": "elbow_flex", "tcp_mm": tcp},
            "cut": {"first_frame": (late or 1) if cut else None, "frames": cut, "last_frame": (late or 1) + cut - 1 if cut else None,
                    "from_start_only": bool(cut) and not late},
            "hand": {"start_rel_mm": [0, h0, 67], "end_rel_mm": [0, h1, 60], "move_rel_mm": [0, h1 - h0, -7], "move_mm": 8.0,
                     "horiz_to_block_start_mm": h0, "horiz_to_block_end_mm": h1, "toward_block_frac": toward,
                     "path_rel_mm": [[0, h0 - 1, 66], [0, h1, 60]]},
            "grip": {"cmd": 35.0, "min": gmin, "max": 35.0},
            "clear": {"sent_if_streamed": {"arm_table": {"min_mm": table}, "jaw_table": {"min_mm": 30.0}, "arm_box": {"min_mm": 150.0},
                                           "arm_block": {"min_mm": 20.0}}}}


class TestReport395(unittest.TestCase):
    def test_judge(self):
        import report_395 as RP
        self.assertEqual(RP.judge(fake_analysis())[0], "(a)")
        self.assertEqual(RP.judge(fake_analysis(jump=7.0, cut=2))[0], "(c) の候補")
        self.assertEqual(RP.judge(fake_analysis(tcp=12.0))[0], "(c) の候補")
        self.assertEqual(RP.judge(fake_analysis(cut=2, late=10))[0], "どちらでもない")     # 後半で切られる (codex R1 A2)
        self.assertEqual(RP.judge(fake_analysis(jump=12.0))[0], "どちらでもない")
        self.assertEqual(RP.judge(fake_analysis(toward=-0.9, h1=16.0))[0], "どちらでもない")
        self.assertEqual(RP.judge(fake_analysis(gmin=20.0))[0], "どちらでもない")
        self.assertEqual(RP.judge(fake_analysis(table=10.0))[0], "どちらでもない")

    def test_build(self):
        import report_395 as RP
        with tempfile.TemporaryDirectory() as d:
            d = Path(d)
            head = "n\tplace\tlap\ttrial\tresult\tfail_reason\ttime\n"
            (d / "progress_395.tsv").write_text(head + "1\t2\t1\tt1\tfirst_only\tfirst_only\tt\n2\t3\t1\tt2\tskip\trefused\tt\n"
                                                "2\t3\t1\tt3\tfirst_only\tfirst_only\tt\n")
            with open(d / R.TRIALS_CSV, "w", newline="") as f:
                w = csv.writer(f)
                w.writerow(COLS)
                for t, an in (("t1", fake_analysis()), ("t2", None), ("t3", fake_analysis(jump=7.0, cut=2))):
                    rd = d / t
                    rd.mkdir()
                    if an:
                        (rd / "first_chunk_395.json").write_text(json.dumps({"frames_wait": 2, "analysis": an,
                                                                             "cut_frames_0based": list(range(an["cut"]["frames"]))}))
                    r = dict.fromkeys(COLS, "")
                    r.update(trial=t, record_dir=str(rd), handover_status="first_only" if an else "refused")
                    w.writerow([r[c] for c in COLS])
            text = RP.build(d, d / "fig.png")
            try:
                import matplotlib  # noqa: F401
                self.assertTrue((d / "fig.png").exists())
            except ImportError:
                self.assertIn("図は描いていない", text)
        self.assertIn("数えた回 2 / 8. 数えなかった回 (動かさずに止めた・途中で止めた) 1", text)
        self.assertIn("| 1 | 2 | 2 | 0.50 |", text)
        self.assertIn("(a)", text)
        self.assertIn("今の記録 (2 回) に当てはめると: **まだ決めない (記録の値が出せた回 2 / 8)**", text)     # codex R1 A2


class TestReport394E5(unittest.TestCase):
    def test_skipped_columns(self):
        import report_394 as RP
        with tempfile.TemporaryDirectory() as d:
            d = Path(d)
            head = "n\tplace\tlap\ttrial\tresult\tfail_reason\ttime\n"
            (d / "progress_394.tsv").write_text(head + "1\t2\t1\th0\tskip\t\tt\n1\t2\t1\th1\tsuccess\t\tt\n2\t3\t1\th2\tskip\t\tt\n"
                                                "2\t3\t1\th3\tskip\t\tt\n2\t3\t1\th4\tfailure\t2\tt\n")
            (d / "progress_385.tsv").write_text(head + "1\t2\t1\tn1\tskip\t\tt\n1\t2\t1\tn2\tsuccess\t\tt\n")
            st = {"h0": "refused", "h1": "handed", "h2": "stopped_code", "h3": "handed", "h4": "handed"}
            with open(d / R.TRIALS_CSV, "w", newline="") as f:
                w = csv.writer(f)
                w.writerow(R.TRIAL_COLUMNS)
                for t in ("h0", "h1", "h2", "h3", "h4", "n1", "n2"):
                    r = dict.fromkeys(R.TRIAL_COLUMNS, "")
                    r.update(trial=t, frames=100, frames_model=50)
                    vals = [r[c] for c in R.TRIAL_COLUMNS]
                    if t in st:
                        h = dict.fromkeys(R.HANDOVER_COLUMNS, "")
                        h.update(handover_status=st[t])
                        vals += [h[c] for c in R.HANDOVER_COLUMNS]
                    w.writerow(vals)
            text = RP.build(d)
        line2 = [ln for ln in text.splitlines() if ln.startswith("| 場所2 | 切り替え |")][0]
        line3 = [ln for ln in text.splitlines() if ln.startswith("| 場所3 | 切り替え |")][0]
        self.assertTrue(line2.endswith("| 1 | 0 | 0 |"), line2)
        self.assertTrue(line3.endswith("| 0 | 1 | 1 |"), line3)
        all_ = [ln for ln in text.splitlines() if ln.startswith("| **場所2〜5** | 切り替え |")][0]
        self.assertTrue(all_.endswith("| 1 | 1 | 1 |"), all_)
        n2 = [ln for ln in text.splitlines() if ln.startswith("| 場所2 | 通常 |")][0]
        self.assertTrue(n2.endswith("| — | — | 1 |"), n2)


class TestSession(unittest.TestCase):
    def test_order(self):
        sh = (HERE / "session_395.sh").read_text()
        self.assertIn("TOTAL=8", sh)
        self.assertIn("PLACE_LIST=(2 3 4 5)", sh)
        self.assertIn("PLAN=so101/check_394/plan_394.json", sh)
        self.assertIn("--first-chunk-only", sh)
        self.assertNotIn("ask_result", sh)
        out = subprocess.run(["bash", "-c", 'PLACE_LIST=(2 3 4 5); PLACES=${#PLACE_LIST[@]}; for n in $(seq 1 8); do '
                              'echo "${PLACE_LIST[$(( (n - 1) % PLACES ))]} $(( (n - 1) / PLACES + 1 ))"; done'],
                             capture_output=True, text=True, check=True).stdout.split("\n")[:-1]
        self.assertEqual(out, [f"{2 + i % 4} {1 + i // 4}" for i in range(8)])
        self.assertEqual(subprocess.run(["bash", "-n", str(HERE / "session_395.sh")]).returncode, 0)


if __name__ == "__main__":
    unittest.main()
