"""依頼 314: ばらつき入りの理想の道の部品のテスト (アーム・カメラ・KIOXIA なし).

  /opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python -m unittest so101/ideal_var/test_ideal_var_314.py
"""
import io
import json
import sys
import tempfile
import unittest
from contextlib import redirect_stdout
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import block_pixel_314 as BP  # noqa: E402
import plan_315 as PL  # noqa: E402
import var_lib_314 as V  # noqa: E402

# 場所1〜5 (依頼 302 の道の ABOVE_BLOCK・GRASP_OPEN と, 依頼 314 で読んだ画素)
PLACES = [
    {"name": "place1", "kind": "place", "u": 367.9, "v": 93.7, "above": [-0.571, 31.561, -23.605, 42.374, -8.484, 35.033],
     "grasp": [-2.768, 52.044, -41.894, 43.956, -10.066, 31.623]},
    {"name": "place2", "kind": "place", "u": 234.8, "v": 164.9, "above": [-20.1, 6.6, 9.4, 33.7, -14.9, 30.3],
     "grasp": [-23.0, 26.9, -0.7, 37.6, -18.6, 29.1]},
    {"name": "place3", "kind": "place", "u": 152.8, "v": 304.0, "above": [-51.6, -1.5, 17.1, 59.6, -6.2, 30.6],
     "grasp": [-51.6, -1.0, 33.4, 39.8, -12.0, 27.7]},
    {"name": "place4", "kind": "place", "u": 272.6, "v": 248.2, "above": [-20.2, -19.0, 31.5, 48.9, -4.7, 5.0],
     "grasp": [-21.0, 0.8, 32.0, 41.9, 2.9, 27.2]},
    {"name": "place5", "kind": "place", "u": 404.4, "v": 151.8, "above": [5.1, 21.1, -2.1, 41.3, -7.3, 27.4],
     "grasp": [5.5, 39.2, -21.6, 53.0, -14.1, 27.8]},
]
LO = np.array([-69.4, -115.1, -106.4, -12.8, -44.2, 0.0])      # お手本 50 本の幅 ±10 (依頼 314 の時点)
HI = np.array([55.2, 68.0, 106.5, 112.2, 35.8, 59.5])
CHAIN = V.load_urdf_chain(V.URDF) if V.URDF.exists() else None



def with_range(plan, calib=None):
    """依頼 345: 割り振りに今の手首の回転の範囲と校正の点の SHA-256 を書く (窓・録るは割り振りと照らし合わせる)"""
    if calib is not None:
        import hashlib
        plan["calib_sha256"] = hashlib.sha256(Path(calib).read_bytes()).hexdigest()
    import run_so101_policy as R
    try:
        lo, hi, _ = V.load_safe_range_var(R.DEFAULT_RAW)
    except FileNotFoundError:
        return plan
    plan["roll_range"] = [round(float(lo[4]), 2), round(float(hi[4]), 2)]
    return plan

class TestInterp(unittest.TestCase):
    def test_tps_exact_at_points_and_smooth(self):
        P = np.array([[0, 0], [10, 0], [0, 10], [10, 10], [5, 3]], float)
        Y = np.c_[P[:, 0] * 2 + P[:, 1], np.sin(P[:, 0])]
        f = V.TPS(P, Y)
        np.testing.assert_allclose(f(P), Y, atol=1e-8)
        lin = V.TPS(P, np.c_[P[:, 0] * 2 + P[:, 1] + 3])       # 一次式はそのまま (一次の項がある)
        np.testing.assert_allclose(lin(np.array([7.0, 2.0])), [19.0], atol=1e-8)

    def test_linear_and_hull(self):
        P = np.array([[0, 0], [10, 0], [0, 10], [10, 10]], float)
        f = V.Linear(P, np.c_[P.sum(1)])
        self.assertAlmostEqual(float(f(np.array([3.0, 4.0]))[0]), 7.0)
        self.assertIsNone(f(np.array([20.0, 4.0])))
        h = V.convex_hull(np.r_[P, [[5, 5]]])
        self.assertEqual(len(h), 4)
        self.assertGreater(V.hull_margin(h, [5, 5]), 4.9)
        self.assertLess(V.hull_margin(h, [12, 5]), 0)

    def test_grasp_map_refuses_outside_and_duplicates(self):
        g = V.GraspMap(PLACES)
        a, b = g([300, 180])
        self.assertEqual(len(a), 5)
        self.assertIsNone(g([600, 50]))
        np.testing.assert_allclose(g([PLACES[1]["u"], PLACES[1]["v"]])[1], PLACES[1]["grasp"][:5], atol=1e-6)
        with self.assertRaises(ValueError):
            V.GraspMap(PLACES + [{**PLACES[0], "name": "dup", "u": PLACES[0]["u"] + 1}])

    def test_leave_one_out_shape(self):
        r = V.leave_one_out(PLACES, names=["place4"])
        self.assertEqual(set(r), {"place4"})
        self.assertFalse(r["place4"]["inside"])         # 場所4 は 5 点の囲みの頂点
        self.assertEqual(len(r["place4"]["grasp_diff"]), 5)


class TestBlockPixel(unittest.TestCase):
    def test_detect_red_square(self):
        img = np.full((480, 640, 3), 200, np.uint8)
        img[100:126, 300:326] = (220, 40, 50)             # RGB の赤
        r, why = BP.detect(img, rgb=True)
        self.assertEqual(why, "")
        self.assertAlmostEqual(r["u"], 312.5, places=1)
        self.assertAlmostEqual(r["v"], 112.5, places=1)
        small = img[::2, ::2].copy()                      # 320×240 の jpg と同じ倍率の直し
        r2, _ = BP.detect(small, rgb=True)
        self.assertAlmostEqual(r2["u"], 312.5, delta=1.0)

    def test_detect_refuses(self):
        img = np.full((480, 640, 3), 200, np.uint8)
        self.assertIsNone(BP.detect(img)[0])
        img[100:126, 300:326] = (220, 40, 50)
        img[300:326, 100:126] = (220, 40, 50)
        r, why = BP.detect(img)
        self.assertIsNone(r)
        self.assertIn("2 つ", why)


@unittest.skipIf(CHAIN is None, "URDF がない")
class TestPath(unittest.TestCase):
    def setUp(self):
        self.g = V.GraspMap(PLACES)
        self.A, _ = V.pixel_mm_affine(PLACES, CHAIN)

    def test_lift_straight_up_and_pull_back(self):
        q, pe, ae, back = V.lift_pose(CHAIN, PLACES[1]["grasp"])
        self.assertLess(pe, 1.0)
        self.assertEqual(back, 0.0)
        dz = V.tcp_mm(CHAIN, q) - V.tcp_mm(CHAIN, PLACES[1]["grasp"])
        np.testing.assert_allclose(dz, [0, 0, V.LIFT_MM], atol=1.0)
        q1, pe1, _, back1 = V.lift_pose(CHAIN, PLACES[0]["grasp"])     # 場所1 は腕を伸ばしきるので引く
        self.assertLess(pe1, 1.0)
        self.assertGreater(back1, 0)
        self.assertAlmostEqual(V.tcp_mm(CHAIN, q1)[2] - V.tcp_mm(CHAIN, PLACES[0]["grasp"])[2], V.LIFT_MM, delta=1.0)

    def test_normal_path_template(self):
        r = V.make_path(self.g, [290, 190], CHAIN, LO, HI)
        self.assertTrue(r["ok"], r["why"])
        p = r["path"]
        self.assertEqual(len(p), 1 + sum(V.TEMPLATE.values()) + V.TEMPLATE_LOWER_BOX)      # 依頼 346: 箱の上の真上から下ろす分
        np.testing.assert_allclose(p[0], V.HOME)
        np.testing.assert_allclose(p[-1], V.HOME)
        kf = {k["name"]: k["frame"] for k in r["keyframes"]}
        np.testing.assert_allclose(p[kf["ABOVE_BOX"], :5], V.ABOVE_BOX)
        np.testing.assert_allclose(p[kf["RELEASED"], :5], V.RELEASED)
        self.assertEqual(kf["CARRY_MID"] - kf["LIFT"], 30)          # 運ぶ 1.0 秒 (依頼 346: 箱の上の真上まで)
        self.assertEqual(kf["ABOVE_BOX"] - kf["CARRY_MID"], V.TEMPLATE_LOWER_BOX)
        self.assertEqual(kf["HOME_END"] - kf["RELEASED"], 30)       # 戻る 1.0 秒
        d = np.abs(np.diff(p, axis=0))
        self.assertLessEqual(d[:, :5].max(), V.STEP_LIMIT_DEG)
        self.assertLessEqual(d[:, 5].max(), V.STEP_LIMIT_GRIP)
        self.assertEqual([x["name"] for x in r["phases"]], [n for n, _ in V.PHASES])
        self.assertEqual(r["phases"][-1]["end"], len(p) - 1)

    def test_offset_and_detour(self):
        off = [6, 7, -6, -7, 5]
        r = V.make_path(self.g, [290, 190], CHAIN, LO, HI, offset=off, detour=(90.0, 25.0), A=self.A)
        self.assertTrue(r["ok"], r["why"])
        np.testing.assert_allclose(r["path"][0, :5], V.HOME[:5] + off)
        self.assertEqual(r["path"][0, 5], V.HOME[5])               # 爪はずらさない
        names = [k["name"] for k in r["keyframes"]]
        self.assertEqual(names[:3], ["HOME", "DETOUR", "ABOVE_BLOCK"])
        self.assertEqual(len(r["path"]), 1 + sum(V.TEMPLATE.values()) + V.DETOUR_BACK + V.TEMPLATE_LOWER_BOX)
        self.assertGreater(r["info"]["detour_tcp_xy_mm"], 15)
        self.assertLess(r["info"]["detour_tcp_xy_mm"], 35)

    def test_refuses(self):
        r = V.make_path(self.g, [600, 40], CHAIN, LO, HI)
        self.assertFalse(r["ok"])
        self.assertIn("範囲の外", r["why"])
        lo = LO.copy()
        lo[3] = 30.0                                                # 手首の下の端を HOME (20°) より上にすると止める
        r = V.make_path(self.g, [290, 190], CHAIN, lo, HI)
        self.assertFalse(r["ok"])
        self.assertIn("wrist_flex", r["why"])

    def test_start_offsets_signs(self):
        rng = np.random.default_rng(0)
        for _ in range(50):
            o = V.start_offsets(rng)
            self.assertTrue(np.all((np.abs(o) >= V.OFFSET_MIN - 1e-9) & (np.abs(o) <= V.OFFSET_MAX + 1e-9)))
            self.assertGreater(o[1], 0)          # 肩は上げる向きだけ
            self.assertLess(o[2], 0)             # 肘は曲げを戻す向きだけ

    def test_plan_is_deterministic_and_spread(self):
        a = PL.make_plan(self.g, PLACES, self.A, seed=1)
        b = PL.make_plan(self.g, PLACES, self.A, seed=1)
        self.assertEqual(a, b)
        eps = a["episodes"]
        self.assertEqual(len(eps), PL.N_EPISODES)
        self.assertEqual(sum(1 for e in eps if e["detour"]), PL.N_EPISODES // PL.DETOUR_EVERY)
        self.assertEqual(sum(1 for e in eps if not any(e["offset"])), PL.N_EPISODES // PL.HOME_EVERY)
        P = np.array([e["pixel"] for e in eps])
        self.assertTrue(all(self.g.inside(p, PL.PLAN_MARGIN_PX - 1e-6) for p in P))
        self.assertFalse(any(PL.in_arm(p) or PL.in_zone(p, PL.BOX_ZONE) for p in P))
        dmin = min(np.linalg.norm(P[i] - P[j]) for i in range(len(P)) for j in range(i))
        self.assertGreater(dmin, 10)           # 散らばっている (同じ所に重ねない)


@unittest.skipIf(CHAIN is None, "URDF がない")
class TestRecordDryFake(unittest.TestCase):
    """record_var_315.py --dry-fake: 範囲の外は録らずに終了コード 3. 中なら 1 本録り, labels に依頼 314 の項目"""

    def test_dry_fake(self):
        try:
            import record_var_315 as RV
        except ImportError as e:
            self.skipTest(f"lerobot の環境でない ({e})")
        with tempfile.TemporaryDirectory() as td:
            td = Path(td)
            calib = td / "calib.json"
            calib.write_text(json.dumps({"made_by": "test", "points": PLACES}))
            g = V.GraspMap(PLACES)
            A, _ = V.pixel_mm_affine(PLACES, CHAIN)
            plan = with_range(PL.make_plan(g, PLACES, A, seed=2), calib)
            (td / "plan.json").write_text(json.dumps(plan))
            common = ["--calib", str(calib), "--plan", str(td / "plan.json"), "--dry-fake", "--local-root", str(td / "ds"),
                      "--kioxia-root", "", "--log-dir", str(td / "log")]
            with redirect_stdout(io.StringIO()):
                self.assertEqual(RV.main(["--index", "0", "--fake-pixel", "600,40"] + common), RV.EXIT_NOT_MADE)
            self.assertFalse((td / "ds").exists())
            with redirect_stdout(io.StringIO()):
                self.assertEqual(RV.main(["--index", "2"] + common), 0)
            lab = json.loads((td / "ds" / "episode_labels.json").read_text())
            self.assertEqual(lab["made_by"], RV.MADE_BY)
            e = lab["episodes"][0]
            self.assertEqual(e["plan_index"], 2)
            self.assertTrue(e["detour"])
            for k in ("block_pixel", "above", "grasp", "start_offset", "label"):
                self.assertIn(k, e)
            self.assertEqual(len(list((td / "log").glob("i02_*_path.json"))), 1)


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