"""依頼 348: 爪の面を机に垂直にする形 (CalcGraspMap level・calc_corr_level) のテスト (アーム・カメラなし. KIOXIA のカメラの値は読む).
作り物の校正の点は test_347 と同じ.

  /opt/homebrew/Caskroom/miniforge/base/envs/lerobot/bin/python -m unittest so101/ideal_var/test_348.py
"""
import sys
import unittest
from pathlib import Path

import numpy as np

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import test_347 as T7  # noqa: E402
import var_lib_314 as V  # noqa: E402

CHAIN = T7.CHAIN


@unittest.skipIf(CHAIN is None, "URDF がない")
class TestLevel(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        import yaw_lib_343 as Y
        cls.Y = Y
        cls.cam = T7.cam_or_skip()
        cls.pts = T7.fake_points(cls.cam)
        cls.g = V.CalcGraspMap(cls.pts, CHAIN, corr=True, cam=cls.cam)
        cls.gl = V.make_grasp_map(cls.pts, "calc_corr_level", CHAIN, cls.cam, elev_max=3.0)
        cls.uv = cls.g.P.mean(0)

    def test_jaw_elev_matches_axis(self):
        """jaw_elev_deg = 爪の閉じる向きの z の角 (手先が真下を向くと JAW_AXIS_TCP の z の分だけ下向き)"""
        q = np.array([0.0, 0.0, 0.0, 0.0, 0.0])
        a = V.fk_T(CHAIN, q)[:3, :3] @ self.Y.JAW_AXIS_TCP
        self.assertAlmostEqual(V.jaw_elev_deg(CHAIN, q), np.degrees(np.arcsin(a[2] / np.linalg.norm(a))), places=6)

    def test_level_makes_jaw_face_vertical_and_keeps_rest(self):
        Y = self.Y
        done = 0
        for yaw in (0.0, 25.0, -30.0):
            q0, i0 = self.g.solve(self.uv, yaw=yaw)
            q, info = self.gl.solve(self.uv, yaw=yaw)
            if q is None:
                continue
            done += 1
            e = V.jaw_elev_deg(CHAIN, self.gl._q(q))
            self.assertLessEqual(abs(e), 3.0 + V.CALC_LEVEL_TOL_DEG)
            self.assertLessEqual(abs(e), abs(V.jaw_elev_deg(CHAIN, self.g._q(q0))) + 1e-6)
            # 爪の間の点・高さ・爪の閉じる向きは level でない形と同じ
            np.testing.assert_allclose(T7.TestCalcGrasp.jaw_point(None, self.gl, q)[:2],
                                       T7.TestCalcGrasp.jaw_point(None, self.g, q0)[:2], atol=1.0)
            self.assertAlmostEqual(V.tcp_arm(CHAIN, self.gl._q(q))[0][2], self.g.grasp_z, delta=1.0)
            self.assertAlmostEqual(Y.fold(Y.jaw_yaw(CHAIN, self.gl._q(q)) - yaw - 90.0), 0.0, delta=1.0)
            self.assertEqual(info["corr_mm"], i0["corr_mm"])        # 直しは依頼 347 と同じ
            self.assertTrue(info["level"])
            self.assertLessEqual(info["tilt_deg"], V.CALC_TILT_RANGE[1] + 1e-6)
        self.assertGreater(done, 0)

    def test_correction_same_as_347(self):
        np.testing.assert_allclose(self.gl.d, self.g.d)
        np.testing.assert_allclose(self.gl.c, self.g.c)

    def test_unreachable_level_is_refused(self):
        """許し 0 で 0 にできない所 (腕を伸ばしきった所で 向きが大きい) は解けない → 道を作らない"""
        g0 = V.make_grasp_map(self.pts, "calc_corr_level", CHAIN, self.cam, elev_max=0.0)
        whys = []
        for uv in self.g.P:
            for yaw in (35.0, -35.0):
                q, info = g0.solve(uv, yaw=yaw)
                if q is None:
                    whys.append(info["why"])
                else:
                    self.assertLessEqual(abs(info["jaw_elev_deg"]), V.CALC_LEVEL_TOL_DEG)
        self.assertTrue(all(("垂直" in w) or ("解けない" in w) or ("範囲" in w) for w in whys), whys)

    def test_mode_and_plan_value(self):
        self.assertIn("calc_corr_level", V.GRASP_MODES)
        g = V.make_grasp_map(self.pts, "calc_level", CHAIN, self.cam, elev_max=4.0)
        self.assertEqual((g.mode, g.corr, g.level, g.elev_max), ("calc_level", False, True, 4.0))
        g = V.make_grasp_map(self.pts, "calc_corr", CHAIN, self.cam)
        self.assertFalse(g.level)
        self.assertEqual(V.level_elev_max_of_plan({}), V.CALC_LEVEL_ELEV_MAX_DEG)
        self.assertEqual(V.level_elev_max_of_plan({"level_elev_max_deg": 8}), 8.0)
        self.assertEqual(V.GRASP_MODE_DEFAULT, "tps")       # 既定は変えない
        d = self.gl.describe()
        self.assertTrue(d["level"])
        self.assertEqual(d["level_elev_max_deg"], 3.0)

    def test_calc_corr_unchanged(self):
        """level でない形 (依頼 347) の答えは 依頼 348 で変わらない (爪の面の傾きは info に出すだけ)"""
        q, info = self.g.solve(self.uv, yaw=20.0)
        self.assertIsNotNone(q)
        self.assertFalse(info["level"])
        self.assertAlmostEqual(info["tilt_deg"], info["tilt_target_deg"], delta=3.0)

    def test_make_path_with_level(self):
        for yaw in (0.0, 20.0):
            r = V.make_path(self.gl, self.uv, CHAIN, T7.LO, T7.HI, yaw=yaw)
            if not r["ok"]:
                self.assertTrue(r["why"])
                continue
            self.assertEqual(r["info"]["grasp_mode"], "calc_corr_level")
            k = {x["name"]: np.array(x["pose"]) for x in r["keyframes"]}
            self.assertLessEqual(abs(V.jaw_elev_deg(CHAIN, self.gl._q(k["GRASP_OPEN"][:5]))), 3.0 + V.CALC_LEVEL_TOL_DEG)


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