from __future__ import annotations

import math
import unittest

from app.schemas import SolveRequest
from app.solver import solve_structure


class StructuralRegressionTests(unittest.TestCase):
    @staticmethod
    def _beam_request(
        *,
        length: float = 6.0,
        rotation_deg: float = 0.0,
        supports: list[dict] | None = None,
        loads: list[dict] | None = None,
        member_point_loads: list[dict] | None = None,
        member_distributed_loads: list[dict] | None = None,
        diagram_points: int = 21,
    ) -> SolveRequest:
        return SolveRequest(
            nodes=[
                {"id": 1, "x": 0.0, "y": 0.0, "z": 0.0},
                {"id": 2, "x": length, "y": 0.0, "z": 0.0},
            ],
            materials=[{"id": 1, "name": "Aco teste", "e": 200e9}],
            elements=[{
                "id": 1,
                "start_node": 1,
                "end_node": 2,
                "material_id": 1,
                "area": 0.01,
                "iy": 8e-6,
                "iz": 2e-6,
                "j": 1e-6,
                "rotation_deg": rotation_deg,
            }],
            supports=supports or [],
            loads=loads or [],
            member_point_loads=member_point_loads or [],
            member_distributed_loads=member_distributed_loads or [],
            diagram_points=diagram_points,
            solver_engine="openseespy",
        )

    def test_opensees_truss_axial_bar_matches_closed_form(self) -> None:
        length = 2.0
        elastic_modulus = 200e9
        area = 0.01
        load = 1000.0

        request = SolveRequest(
            nodes=[
                {"id": 1, "x": 0.0, "y": 0.0, "z": 0.0},
                {"id": 2, "x": length, "y": 0.0, "z": 0.0},
            ],
            materials=[{"id": 1, "name": "Aco teste", "e": elastic_modulus}],
            elements=[
                {
                    "id": 1,
                    "start_node": 1,
                    "end_node": 2,
                    "material_id": 1,
                    "area": area,
                    "start_release_ry": True,
                    "start_release_rz": True,
                    "end_release_ry": True,
                    "end_release_rz": True,
                }
            ],
            supports=[
                {"node_id": 1, "ux": {"mode": "fixed"}, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
                {"node_id": 2, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
            ],
            loads=[{"node_id": 2, "fx": load}],
            solver_engine="openseespy",
        )

        result = solve_structure(request)
        node_2 = next(item for item in result.displacements if item.node_id == 2)
        element = result.element_forces[0]

        expected_ux = (load * length) / (elastic_modulus * area)
        self.assertTrue(math.isclose(node_2.ux, expected_ux, rel_tol=1e-9, abs_tol=1e-12))
        self.assertTrue(math.isclose(element.axial_force, load, rel_tol=1e-9, abs_tol=1e-9))
        self.assertTrue(math.isclose(element.stress, load / area, rel_tol=1e-9, abs_tol=1e-6))
        self.assertEqual(result.engine, "openseespy/truss")

    def test_fully_released_frame_routes_to_opensees_axial_truss(self) -> None:
        base_request = {
            "nodes": [
                {"id": 1, "x": 0.0, "y": 0.0, "z": 0.0},
                {"id": 2, "x": 1.0, "y": 0.0, "z": 0.0},
                {"id": 3, "x": 0.0, "y": 1.0, "z": 0.0},
            ],
            "materials": [{"id": 1, "name": "Aco teste", "e": 200e9}],
            "elements": [
                {
                    "id": 1,
                    "start_node": 1,
                    "end_node": 2,
                    "material_id": 1,
                    "area": 1e-3,
                    "start_release_ry": True,
                    "start_release_rz": True,
                    "end_release_ry": True,
                    "end_release_rz": True,
                },
                {
                    "id": 2,
                    "start_node": 2,
                    "end_node": 3,
                    "material_id": 1,
                    "area": 1e-3,
                    "start_release_ry": True,
                    "start_release_rz": True,
                    "end_release_ry": True,
                    "end_release_rz": True,
                },
                {
                    "id": 3,
                    "start_node": 3,
                    "end_node": 1,
                    "material_id": 1,
                    "area": 1e-3,
                    "start_release_ry": True,
                    "start_release_rz": True,
                    "end_release_ry": True,
                    "end_release_rz": True,
                },
            ],
            "supports": [
                {"node_id": 1, "ux": {"mode": "fixed"}, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
                {"node_id": 2, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
                {"node_id": 3, "uz": {"mode": "fixed"}},
            ],
            "loads": [{"node_id": 3, "fx": 1000.0}],
        }

        request = SolveRequest(**base_request, solver_engine="openseespy")
        result = solve_structure(request)

        self.assertEqual(result.engine, "openseespy/truss")
        self.assertGreater(result.summary.max_axial_force, 0.0)
        self.assertEqual(result.summary.max_bending_moment, 0.0)

    def test_future_engines_are_explicitly_unavailable(self) -> None:
        base_request = {
            "nodes": [
                {"id": 1, "x": 0.0, "y": 0.0, "z": 0.0},
                {"id": 2, "x": 1.0, "y": 0.0, "z": 0.0},
            ],
            "materials": [{"id": 1, "name": "Aco teste", "e": 200e9}],
            "elements": [
                {"id": 1, "start_node": 1, "end_node": 2, "material_id": 1, "area": 1e-3}
            ],
        }
        for engine in ("pynite", "native_truss"):
            with self.subTest(engine=engine):
                with self.assertRaisesRegex(ValueError, "fase futura"):
                    solve_structure(SolveRequest(**base_request, solver_engine=engine))

    def test_manual_combination_scales_cases_and_records_trace(self) -> None:
        request = SolveRequest(
            nodes=[
                {"id": 1, "x": 0.0, "y": 0.0, "z": 0.0},
                {"id": 2, "x": 2.0, "y": 0.0, "z": 0.0},
            ],
            materials=[{"id": 1, "name": "Aco teste", "e": 200e9}],
            elements=[{
                "id": 1,
                "start_node": 1,
                "end_node": 2,
                "material_id": 1,
                "area": 0.01,
                "start_release_ry": True,
                "start_release_rz": True,
                "end_release_ry": True,
                "end_release_rz": True,
                "buckling_ky": 1.2,
            }],
            supports=[
                {"node_id": 1, "ux": {"mode": "fixed"}, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
                {"node_id": 2, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
            ],
            loads=[
                {"node_id": 2, "load_case_id": "permanent", "fx": 1000.0, "gamma": 1.4},
                {"node_id": 2, "load_case_id": "live", "fx": 500.0, "gamma": 1.5},
                {"node_id": 2, "load_case_id": "wind", "fx": 9999.0},
            ],
            load_cases=[
                {"id": "permanent", "name": "Permanente", "kind": "dead"},
                {"id": "live", "name": "Sobrecarga", "kind": "live"},
                {"id": "wind", "name": "Vento", "kind": "wind", "enabled": False},
            ],
            combination={
                "id": "elu_manual",
                "name": "ELU manual de teste",
                "kind": "manual",
                "factors": {"permanent": 1.4, "live": 1.5, "wind": 2.0},
                "standard_ref": "criterio fornecido pelo usuario",
            },
            solver_engine="openseespy",
        )

        result = solve_structure(request)
        self.assertTrue(math.isclose(result.element_forces[0].axial_force, 2150.0, abs_tol=1e-8))
        self.assertIsNotNone(result.analysis)
        self.assertEqual(
            result.analysis.factors,
            {"live": 1.5, "permanent": 1.4, "wind": 0.0},
        )
        self.assertFalse(result.analysis.normative_design_performed)
        self.assertEqual(len(result.analysis.model_sha256), 64)
        self.assertTrue(any("gamma/qc" in note for note in result.notes))
        self.assertTrue(any("flambagem" in note for note in result.notes))

    def test_uniform_load_matches_simply_supported_beam_equilibrium(self) -> None:
        length = 6.0
        load_per_length = -1000.0
        request = self._beam_request(
            length=length,
            supports=[
                {
                    "node_id": 1,
                    "ux": {"mode": "fixed"},
                    "uy": {"mode": "fixed"},
                    "uz": {"mode": "fixed"},
                    "rx": {"mode": "fixed"},
                },
                {"node_id": 2, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
            ],
            member_distributed_loads=[{
                "element_id": 1,
                "direction": "Fz",
                "w1": load_per_length,
                "w2": load_per_length,
                "x1": 0.0,
                "x2": length,
            }],
        )

        result = solve_structure(request)
        reactions = {reaction.node_id: reaction for reaction in result.reactions}
        expected_reaction = abs(load_per_length) * length / 2.0
        self.assertTrue(math.isclose(reactions[1].rz, expected_reaction, abs_tol=1e-8))
        self.assertTrue(math.isclose(reactions[2].rz, expected_reaction, abs_tol=1e-8))
        midpoint = result.element_diagrams[0].points[len(result.element_diagrams[0].points) // 2]
        expected_moment = abs(load_per_length) * length**2 / 8.0
        self.assertTrue(math.isclose(midpoint.moment_y, expected_moment, abs_tol=1e-8))
        self.assertTrue(math.isclose(result.element_diagrams[0].points[0].moment_y, 0.0, abs_tol=1e-8))
        self.assertTrue(math.isclose(result.element_diagrams[0].points[-1].moment_y, 0.0, abs_tol=1e-8))

    def test_uniform_load_keeps_exact_zero_shear_station_with_two_diagram_points(self) -> None:
        length = 10.0
        load_per_length = -20_000.0
        request = self._beam_request(
            length=length,
            supports=[
                {
                    "node_id": 1,
                    "ux": {"mode": "fixed"},
                    "uy": {"mode": "fixed"},
                    "uz": {"mode": "fixed"},
                    "rx": {"mode": "fixed"},
                },
                {"node_id": 2, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
            ],
            member_distributed_loads=[
                {
                    "element_id": 1,
                    "direction": "Fz",
                    "w1": load_per_length,
                    "w2": load_per_length,
                    "x1": 0.0,
                    "x2": length,
                }
            ],
            diagram_points=2,
        )

        result = solve_structure(request)

        expected_shear = abs(load_per_length) * length / 2.0
        expected_moment = abs(load_per_length) * length**2 / 8.0
        midpoint = next(
            point
            for point in result.element_diagrams[0].points
            if math.isclose(point.x, length / 2.0, abs_tol=1.0e-10)
        )
        self.assertTrue(math.isclose(midpoint.shear_z, 0.0, abs_tol=1.0e-8))
        self.assertTrue(
            math.isclose(abs(midpoint.moment_y), expected_moment, rel_tol=1.0e-12)
        )
        self.assertTrue(
            math.isclose(result.summary.max_shear_force, expected_shear, rel_tol=1.0e-12)
        )
        self.assertTrue(
            math.isclose(
                result.summary.max_bending_moment,
                expected_moment,
                rel_tol=1.0e-12,
            )
        )

    def test_off_grid_point_load_peak_does_not_depend_on_diagram_resolution(self) -> None:
        length = 6.0
        load_position = 2.123
        load = -1000.0
        request = self._beam_request(
            length=length,
            supports=[
                {
                    "node_id": 1,
                    "ux": {"mode": "fixed"},
                    "uy": {"mode": "fixed"},
                    "uz": {"mode": "fixed"},
                    "rx": {"mode": "fixed"},
                },
                {"node_id": 2, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
            ],
            member_point_loads=[{
                "element_id": 1,
                "direction": "Fz",
                "value": load,
                "x": load_position,
            }],
            diagram_points=2,
        )

        result = solve_structure(request)
        expected_moment = abs(load) * load_position * (length - load_position) / length
        self.assertTrue(
            math.isclose(result.summary.max_bending_moment, expected_moment, rel_tol=1e-10)
        )
        diagram_positions = [point.x for point in result.element_diagrams[0].points]
        self.assertIn(load_position, diagram_positions)

    def test_internal_point_load_preserves_both_sides_and_exact_axial_maximum(self) -> None:
        length = 5.0
        load_position = 4.0
        distributed_load = -100.0
        point_load = 500.0
        request = self._beam_request(
            length=length,
            supports=[
                {
                    "node_id": 1,
                    "ux": {"mode": "fixed"},
                    "uy": {"mode": "fixed"},
                    "uz": {"mode": "fixed"},
                    "rx": {"mode": "fixed"},
                },
                {"node_id": 2, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
            ],
            member_point_loads=[{
                "element_id": 1,
                "direction": "Fx",
                "value": point_load,
                "x": load_position,
            }],
            member_distributed_loads=[{
                "element_id": 1,
                "direction": "Fx",
                "w1": distributed_load,
                "w2": distributed_load,
                "x1": 0.0,
                "x2": length,
            }],
            diagram_points=2,
        )

        result = solve_structure(request)
        points = result.element_diagrams[0].points
        at_load = [point for point in points if math.isclose(point.x, load_position, abs_tol=1e-12)]
        expected_before = -distributed_load * load_position
        expected_after = expected_before - point_load

        self.assertEqual(sum(math.isclose(point.x, 0.0, abs_tol=1e-12) for point in points), 1)
        self.assertEqual(sum(math.isclose(point.x, length, abs_tol=1e-12) for point in points), 1)
        self.assertEqual(len(at_load), 2)
        self.assertTrue(math.isclose(at_load[0].axial, expected_before, abs_tol=1e-8))
        self.assertTrue(math.isclose(at_load[1].axial, expected_after, abs_tol=1e-8))
        self.assertTrue(
            math.isclose(
                result.summary.max_axial_force,
                max(abs(expected_before), abs(expected_after)),
                abs_tol=1e-8,
            )
        )

    def test_end_point_load_preserves_the_internal_side_and_exact_axial_maximum(self) -> None:
        length = 5.0
        distributed_load = -100.0
        point_load = 500.0
        request = self._beam_request(
            length=length,
            supports=[
                {
                    "node_id": 1,
                    "ux": {"mode": "fixed"},
                    "uy": {"mode": "fixed"},
                    "uz": {"mode": "fixed"},
                    "rx": {"mode": "fixed"},
                },
                {"node_id": 2, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
            ],
            member_point_loads=[{
                "element_id": 1,
                "direction": "Fx",
                "value": point_load,
                "x": length,
            }],
            member_distributed_loads=[{
                "element_id": 1,
                "direction": "Fx",
                "w1": distributed_load,
                "w2": distributed_load,
                "x1": 0.0,
                "x2": length,
            }],
            diagram_points=2,
        )

        result = solve_structure(request)
        points = result.element_diagrams[0].points
        at_end = [point for point in points if math.isclose(point.x, length, abs_tol=1e-12)]
        expected_inside = -distributed_load * length
        expected_after_load = expected_inside - point_load

        self.assertEqual(len(at_end), 2)
        self.assertTrue(math.isclose(at_end[0].axial, expected_inside, abs_tol=1e-8))
        self.assertTrue(math.isclose(at_end[1].axial, expected_after_load, abs_tol=1e-8))
        self.assertTrue(
            math.isclose(result.summary.max_axial_force, expected_inside, abs_tol=1e-8)
        )
        self.assertTrue(
            math.isclose(result.element_forces[0].axial_end, at_end[-1].axial, abs_tol=1e-8)
        )

    def test_partial_trapezoidal_load_preserves_resultant_and_centroid(self) -> None:
        length = 8.0
        x1 = 1.0
        x2 = 5.0
        w1 = -200.0
        w2 = -1000.0
        request = self._beam_request(
            length=length,
            supports=[
                {
                    "node_id": 1,
                    "ux": {"mode": "fixed"},
                    "uy": {"mode": "fixed"},
                    "uz": {"mode": "fixed"},
                    "rx": {"mode": "fixed"},
                },
                {"node_id": 2, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
            ],
            member_distributed_loads=[{
                "element_id": 1,
                "direction": "Fz",
                "w1": w1,
                "w2": w2,
                "x1": x1,
                "x2": x2,
            }],
        )

        result = solve_structure(request)
        reactions = {reaction.node_id: reaction for reaction in result.reactions}
        span = x2 - x1
        resultant = abs(w1 + w2) * span * 0.5
        local_first_moment = (
            abs(w1) * span**2 * 0.5
            + (abs(w2) - abs(w1)) * span**2 / 3.0
        )
        centroid = x1 + local_first_moment / resultant
        expected_right = resultant * centroid / length
        expected_left = resultant - expected_right

        self.assertTrue(math.isclose(reactions[1].rz, expected_left, rel_tol=5e-4))
        self.assertTrue(math.isclose(reactions[2].rz, expected_right, rel_tol=5e-4))
        self.assertTrue(any("discretizadas" in note for note in result.notes))

    def test_section_rotation_switches_cantilever_bending_inertia(self) -> None:
        length = 3.0
        tip_load = -1000.0
        fixed_support = [{
            "node_id": 1,
            "ux": {"mode": "fixed"},
            "uy": {"mode": "fixed"},
            "uz": {"mode": "fixed"},
            "rx": {"mode": "fixed"},
            "ry": {"mode": "fixed"},
            "rz": {"mode": "fixed"},
        }]
        displacements = []
        for rotation in (0.0, 90.0):
            result = solve_structure(self._beam_request(
                length=length,
                rotation_deg=rotation,
                supports=fixed_support,
                loads=[{"node_id": 2, "fz": tip_load}],
            ))
            displacements.append(next(item.uz for item in result.displacements if item.node_id == 2))

        expected_strong = tip_load * length**3 / (3.0 * 200e9 * 8e-6)
        expected_weak = tip_load * length**3 / (3.0 * 200e9 * 2e-6)
        self.assertTrue(math.isclose(displacements[0], expected_strong, rel_tol=1e-10))
        self.assertTrue(math.isclose(displacements[1], expected_weak, rel_tol=1e-10))

    def test_mixed_frame_summary_counts_automatic_rotation_constraints(self) -> None:
        request = SolveRequest(
            nodes=[
                {"id": 1, "x": 0.0, "y": 0.0, "z": 0.0},
                {"id": 2, "x": 1.0, "y": 0.0, "z": 0.0},
                {"id": 3, "x": 2.0, "y": 0.0, "z": 0.0},
            ],
            materials=[{"id": 1, "name": "Aco teste", "e": 200e9}],
            elements=[
                {
                    "id": 1,
                    "start_node": 1,
                    "end_node": 2,
                    "material_id": 1,
                    "area": 0.01,
                    "iy": 8e-6,
                    "iz": 2e-6,
                    "j": 1e-6,
                },
                {
                    "id": 2,
                    "start_node": 2,
                    "end_node": 3,
                    "material_id": 1,
                    "area": 0.01,
                    "iy": 8e-6,
                    "iz": 2e-6,
                    "j": 1e-6,
                    "start_release_ry": True,
                    "start_release_rz": True,
                    "end_release_ry": True,
                    "end_release_rz": True,
                },
            ],
            supports=[
                {
                    "node_id": 1,
                    "ux": {"mode": "fixed"},
                    "uy": {"mode": "fixed"},
                    "uz": {"mode": "fixed"},
                    "rx": {"mode": "fixed"},
                    "ry": {"mode": "fixed"},
                    "rz": {"mode": "fixed"},
                },
                {"node_id": 3, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}},
            ],
            loads=[{"node_id": 3, "fx": 1000.0}],
            solver_engine="openseespy",
        )

        result = solve_structure(request)
        self.assertEqual(result.summary.dof_count, 18)
        self.assertEqual(result.summary.constrained_dof_count, 11)
        self.assertEqual(result.summary.free_dof_count, 7)


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