"""Pruebas de support_polygon.py."""
import unittest

import math

from support_polygon import (convex_hull, distance_point_segment, inside_convex, max_lateral_accel,
                             min_margin_over_cycle, static_stability_margin, tipover_angles)

SQUARE = [(0.1, 0.1), (-0.1, 0.1), (-0.1, -0.1), (0.1, -0.1)]


class SupportPolygonTest(unittest.TestCase):
    def test_hull_removes_interior_and_collinear(self):
        hull = convex_hull(SQUARE + [(0.0, 0.0), (0.0, 0.1)])
        self.assertEqual(len(hull), 4)
        self.assertTrue(all(p in hull for p in SQUARE))

    def test_center_margin_is_half_side(self):
        self.assertAlmostEqual(static_stability_margin((0.0, 0.0), SQUARE), 0.1)

    def test_offset_cog(self):
        self.assertAlmostEqual(static_stability_margin((0.03, 0.0), SQUARE), 0.07)

    def test_outside_is_negative(self):
        self.assertAlmostEqual(static_stability_margin((0.15, 0.0), SQUARE), -0.05)

    def test_triangle(self):
        tri = [(0.12, 0.0), (-0.06, 0.104), (-0.06, -0.104)]
        m = static_stability_margin((0.0, 0.0), tri)
        self.assertAlmostEqual(m, 0.06, places=3)  # inradio del triángulo (casi) equilátero
        self.assertTrue(inside_convex((0.0, 0.0), convex_hull(tri)))

    def test_two_contacts_not_statically_stable(self):
        self.assertLessEqual(static_stability_margin((0.0, 0.0), [(0.1, 0.0), (-0.1, 0.0)]), 0.0)
        self.assertLess(static_stability_margin((0.0, 0.05), [(0.1, 0.0), (-0.1, 0.0)]), 0.0)

    def test_distance_segment_endpoints(self):
        self.assertAlmostEqual(distance_point_segment((2.0, 0.0), (0.0, 0.0), (1.0, 0.0)), 1.0)
        self.assertAlmostEqual(distance_point_segment((0.5, 1.0), (0.0, 0.0), (1.0, 0.0)), 1.0)

    def test_tipover_square(self):
        angles = tipover_angles((0.0, 0.0), 0.1, SQUARE)
        self.assertEqual(len(angles), 4)
        for *_, a in angles:
            self.assertAlmostEqual(a, math.pi / 4)  # d = h = 0,1 m
        self.assertAlmostEqual(max_lateral_accel((0.0, 0.0), 0.1, SQUARE), 9.80665)
        with self.assertRaises(ValueError):
            tipover_angles((0.2, 0.0), 0.1, SQUARE)

    def test_cycle_minimum(self):
        m, idx = min_margin_over_cycle([(0, 0), (0.05, 0.0)], [SQUARE, SQUARE])
        self.assertEqual(idx, 1)
        self.assertAlmostEqual(m, 0.05)
        with self.assertRaises(ValueError):
            min_margin_over_cycle([], [])


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