from __future__ import annotations

from collections import Counter
import math
import unittest

from app.project_analysis import solve_project
from app.engines.opensees_engine import ElementRuntimeInfo, OpenSeesPyEngine
from app.model_codec import decode_solve_response, encode_solve_response
from app.schemas import (
    Element,
    ElementDeflection,
    ElementDiagram,
    ElementDiagramPoint,
    ElementForce,
    MemberDistributedLoad,
    NodeDisplacement,
    ProjectAnalysisSettings,
    SolveAnalysisInfo,
    SolveCombination,
    SolveRequest,
    SolveResponse,
    SolveSummary,
)


def _combination(
    identifier: str,
    *,
    limit_state: str,
    factors: dict[str, float],
) -> SolveCombination:
    return SolveCombination(
        id=identifier,
        name=identifier.upper(),
        kind="automatic",
        limit_state=limit_state,
        situation="service" if limit_state.startswith("sls_") else "persistent",
        factors=factors,
        standard_ref="ABNT NBR 8681:2025",
        source="generated",
    )


def _request(
    combinations: list[SolveCombination],
    *,
    tension_only: bool = False,
    second_order: bool = False,
    verify_profiles: bool = False,
    deflection_ratio_limit: float | None = None,
    strategy: str = "auto",
    declare_design_data: bool = True,
) -> SolveRequest:
    return SolveRequest.model_validate(
        {
            "nodes": [
                {"id": 1, "x": 0.0, "y": 0.0, "z": 0.0},
                {"id": 2, "x": 5.0, "y": 0.0, "z": 0.0},
            ],
            "materials": [
                {
                    "id": 1,
                    "name": "ASTM A572 Grau 50",
                    "e": 200e9,
                    "g": 77e9,
                    "nu": 0.30,
                    "rho": 7850.0,
                    "fy": 345e6,
                    "fu": 450e6,
                }
            ],
            "sections": [
                {
                    "id": 1,
                    "name": "W 310 x 32,7",
                    "source": "catalogo",
                    "shape": "wide_flange_i",
                    "manufacturing_process": "hot_rolled",
                    "profile_id": "W310X32.7",
                    "area": 0.00418,
                    "iy": 6.57e-5,
                    "iz": 5.50e-6,
                    "j": 1.45e-7,
                    "depth_m": 0.31,
                    "flange_width_m": 0.165,
                    "web_thickness_m": 0.0058,
                    "flange_thickness_m": 0.0097,
                    "clear_web_height_m": 0.2906,
                    "fillet_clear_web_height_m": 0.27,
                    "elastic_modulus_strong_m3": 4.24e-4,
                    "elastic_modulus_weak_m3": 6.67e-5,
                    "plastic_modulus_strong_m3": 4.75e-4,
                    "plastic_modulus_weak_m3": 1.03e-4,
                    "warping_constant_m6": 1.1e-7,
                }
            ],
            "elements": [
                {
                    "id": 1,
                    "start_node": 1,
                    "end_node": 2,
                    "material_id": 1,
                    "section_id": 1,
                    "section_name": "W 310 x 32,7",
                    "area": 0.00418,
                    "iy": 6.57e-5,
                    "iz": 5.50e-6,
                    "j": 1.45e-7,
                    "tension_only": tension_only,
                    "design_connection_mode": "full_section",
                    "design_continuous_lateral_restraint": True,
                    "deflection_ratio_limit": deflection_ratio_limit,
                    **(
                        {
                            "buckling_kx": 1.0,
                            "buckling_ky": 1.0,
                            "buckling_kz": 1.0,
                            "design_transverse_load_position": "centroid",
                            "design_localized_transverse_forces": "absent",
                        }
                        if declare_design_data
                        else {}
                    ),
                }
            ],
            "load_cases": [
                {"id": "dead", "name": "Permanente", "kind": "dead"},
                {"id": "live", "name": "Sobrecarga", "kind": "live"},
            ],
            "combination": combinations[0],
            "combinations": combinations,
            "project_analysis": ProjectAnalysisSettings(
                enabled=True,
                strategy=strategy,
                second_order=second_order,
                verify_profiles=verify_profiles,
            ),
            "solver_engine": "openseespy",
        }
    )


class FakeSolver:
    def __init__(self, *, fail_ids: set[str] | None = None, deflection_scale: float = 0.001):
        self.calls: list[tuple[str, str]] = []
        self.fail_ids = fail_ids or set()
        self.deflection_scale = deflection_scale

    def __call__(self, request: SolveRequest) -> SolveResponse:
        combination = request.combination
        self.calls.append((combination.id, request.analysis_order))
        if combination.id in self.fail_ids:
            raise ValueError(f"falha controlada em {combination.id}")
        base = (
            combination.factors.get("dead", 0.0) * 10.0
            + combination.factors.get("live", 0.0) * -4.0
        )
        order_factor = 1.2 if request.analysis_order == "second_order" else 1.0
        axial = base * 1_000.0 * order_factor
        displacement = abs(base) * self.deflection_scale * order_factor
        point_values = [
            ElementDiagramPoint(
                x=0.0,
                axial=axial,
                shear_y=base * 100.0,
                shear_z=0.0,
                torsion=0.0,
                moment_y=0.0,
                moment_z=base * 500.0,
            ),
            ElementDiagramPoint(
                x=5.0,
                axial=axial,
                shear_y=-base * 100.0,
                shear_z=0.0,
                torsion=0.0,
                moment_y=0.0,
                moment_z=-base * 250.0,
            ),
        ]
        return SolveResponse(
            engine="fake/frame",
            displacements=[
                NodeDisplacement(node_id=1, ux=0, uy=0, uz=0, rx=0, ry=0, rz=0, magnitude=0),
                NodeDisplacement(
                    node_id=2,
                    ux=displacement,
                    uy=0,
                    uz=0,
                    rx=0,
                    ry=0,
                    rz=0,
                    magnitude=displacement,
                ),
            ],
            reactions=[],
            element_forces=[
                ElementForce(
                    element_id=1,
                    start_node=1,
                    end_node=2,
                    length=5.0,
                    axial_force=axial,
                    stress=axial / 0.00418,
                    strain=axial / (0.00418 * 200e9),
                    state="tracao" if axial >= 0 else "compressao",
                    axial_start=axial,
                    axial_end=axial,
                    shear_y_start=point_values[0].shear_y,
                    shear_y_end=point_values[1].shear_y,
                    shear_z_start=0,
                    shear_z_end=0,
                    torsion_start=0,
                    torsion_end=0,
                    moment_y_start=0,
                    moment_y_end=0,
                    moment_z_start=point_values[0].moment_z,
                    moment_z_end=point_values[1].moment_z,
                )
            ],
            element_diagrams=[
                ElementDiagram(
                    element_id=1,
                    start_node=1,
                    end_node=2,
                    length=5.0,
                    points=point_values,
                )
            ],
            element_deflections=[
                ElementDeflection(
                    element_id=1,
                    start_node=1,
                    end_node=2,
                    length=5.0,
                    local_y_max_abs=displacement,
                    local_y_position=2.5,
                    local_z_max_abs=0,
                    local_z_position=0,
                    resultant_max_abs=displacement,
                    resultant_position=2.5,
                )
            ],
            summary=SolveSummary(
                node_count=2,
                element_count=1,
                dof_count=12,
                constrained_dof_count=6,
                free_dof_count=6,
                max_displacement=displacement,
                max_axial_force=abs(axial),
                max_shear_force=abs(base * 100.0),
                max_bending_moment=abs(base * 500.0),
                max_torsion=0,
            ),
            analysis=SolveAnalysisInfo(
                combination_id=combination.id,
                combination_name=combination.name,
                combination_kind=combination.kind,
                limit_state=combination.limit_state,
                situation=combination.situation,
                leading_case_id=combination.leading_case_id,
                factors=combination.factors,
                standard_ref=combination.standard_ref,
                app_revision="teste",
                engine_version="teste",
                model_sha256="0" * 64,
                units={"length": "m", "force": "N", "moment": "N.m"},
                calculated_at="2026-07-21T12:00:00+00:00",
                duration_ms=1,
                analysis_order=request.analysis_order,
            ),
            result_detail="full",
        )


class AdaptiveAnalysisOps:
    def __init__(self, maximum_convergent_step: float):
        self.maximum_convergent_step = maximum_convergent_step
        self.time = 0.0
        self.step = 0.0
        self.attempted_steps: list[float] = []
        self.test_names: list[str] = []

    def reset(self) -> None:
        self.time = 0.0

    def setTime(self, value: float) -> None:
        self.time = float(value)

    def wipeAnalysis(self) -> None:
        pass

    def constraints(self, *_args) -> None:
        pass

    def numberer(self, *_args) -> None:
        pass

    def system(self, *_args) -> None:
        pass

    def analysis(self, *_args) -> None:
        pass

    def test(self, name: str, *_args) -> None:
        self.test_names.append(name)

    def algorithm(self, *_args) -> None:
        pass

    def integrator(self, _name: str, step: float) -> None:
        self.step = float(step)

    def analyze(self, _steps: int) -> int:
        self.attempted_steps.append(self.step)
        if self.step > self.maximum_convergent_step + 1.0e-12:
            return -1
        self.time += self.step * _steps
        return 0

    def getTime(self) -> float:
        return self.time


class ProjectAnalysisTests(unittest.TestCase):
    def test_nonlinear_analysis_restarts_with_finer_increment_until_convergence(self) -> None:
        ops = AdaptiveAnalysisOps(maximum_convergent_step=0.05)

        OpenSeesPyEngine._run_nonlinear_static_analysis(
            ops,
            need_full_matrix=False,
            load_increments=10,
            description="ensaio adaptativo",
        )

        self.assertAlmostEqual(ops.time, 1.0, places=10)
        self.assertIn(0.1, ops.attempted_steps)
        self.assertIn(0.05, ops.attempted_steps)
        self.assertTrue(ops.test_names)
        self.assertEqual(set(ops.test_names), {"NormDispIncr"})

    def test_nonlinear_analysis_keeps_physical_steps_for_factored_combination(self) -> None:
        ops = AdaptiveAnalysisOps(maximum_convergent_step=0.1000001)

        OpenSeesPyEngine._run_nonlinear_static_analysis(
            ops,
            need_full_matrix=False,
            load_increments=10,
            target_load_factor=1.4,
            description="ELU fatorada",
        )

        self.assertAlmostEqual(ops.time, 1.4, places=10)
        self.assertAlmostEqual(ops.attempted_steps[0], 0.1, places=12)

    def test_nonlinear_load_path_scale_uses_and_limits_combination_factor(self) -> None:
        regular = _request([
            _combination("uls_regular", limit_state="uls_normal", factors={"dead": 1.4})
        ])
        extreme = regular.model_copy(
            update={
                "combination": _combination(
                    "uls_extreme",
                    limit_state="uls_normal",
                    factors={"dead": 100.0},
                )
            }
        )

        self.assertAlmostEqual(OpenSeesPyEngine._nonlinear_load_path_scale(regular), 1.4)
        self.assertAlmostEqual(OpenSeesPyEngine._nonlinear_load_path_scale(extreme), 4.0)

    def test_moment_integration_recovers_constant_curvature_deflection(self) -> None:
        length = 4.0
        elastic_modulus = 200e9
        inertia = 8.0e-6
        moment = 32_000.0
        element = Element(
            id=1,
            start_node=1,
            end_node=2,
            material_id=1,
            area=0.01,
            iy=inertia,
            iz=inertia,
            j=1.0e-5,
        )
        runtime = ElementRuntimeInfo(
            element=element,
            material_e=elastic_modulus,
            length=length,
            x_axis=(1.0, 0.0, 0.0),
            y_axis=(0.0, 1.0, 0.0),
            z_axis=(0.0, 0.0, 1.0),
            iy=inertia,
            iz=inertia,
        )

        result = OpenSeesPyEngine._element_deflection_from_moment_samples(
            runtime,
            [(0.0, 0.0, moment), (length, 0.0, moment)],
        )

        expected = moment * length**2 / (8.0 * elastic_modulus * inertia)
        self.assertAlmostEqual(result.local_y_max_abs, expected, places=12)
        self.assertAlmostEqual(result.local_y_position, length * 0.5, places=12)

    def test_fixed_fixed_uniform_load_recovers_analytical_member_deflection(self) -> None:
        length = 6.0
        elastic_modulus = 200e9
        inertia = 8.0e-6
        load = -10_000.0
        fixed = {
            dof: {"mode": "fixed"}
            for dof in ("ux", "uy", "uz", "rx", "ry", "rz")
        }
        request = SolveRequest.model_validate(
            {
                "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",
                        "e": elastic_modulus,
                        "g": 77e9,
                        "rho": 7850.0,
                    }
                ],
                "elements": [
                    {
                        "id": 1,
                        "start_node": 1,
                        "end_node": 2,
                        "material_id": 1,
                        "area": 0.01,
                        "iy": inertia,
                        "iz": inertia,
                        "j": 1.0e-5,
                    }
                ],
                "supports": [
                    {"node_id": 1, **fixed},
                    {"node_id": 2, **fixed},
                ],
                "member_distributed_loads": [
                    {
                        "element_id": 1,
                        "load_case_id": "dead",
                        "direction": "Fz",
                        "w1": load,
                        "w2": load,
                        "x1": 0.0,
                        "x2": length,
                    }
                ],
                "load_cases": [
                    {"id": "dead", "name": "Permanente", "kind": "dead"}
                ],
                "combination": {
                    "id": "sls",
                    "name": "ELS",
                    "kind": "manual",
                    "limit_state": "sls_rare",
                    "situation": "service",
                    "factors": {"dead": 1.0},
                },
                "solver_engine": "openseespy",
                "diagram_points": 41,
            }
        )

        response = OpenSeesPyEngine().solve(request)

        expected = abs(load) * length**4 / (384.0 * elastic_modulus * inertia)
        actual = response.element_deflections[0].resultant_max_abs
        self.assertAlmostEqual(actual / expected, 1.0, delta=2.0e-4)

    def test_opensees_pdelta_amplifies_compressed_cantilever_sway(self) -> None:
        fixed = {
            dof: {"mode": "fixed"}
            for dof in ("ux", "uy", "uz", "rx", "ry", "rz")
        }
        request = SolveRequest.model_validate(
            {
                "nodes": [
                    {"id": 1, "x": 0.0, "y": 0.0, "z": 0.0},
                    {"id": 2, "x": 0.0, "y": 0.0, "z": 3.0},
                ],
                "materials": [
                    {"id": 1, "name": "Aco", "e": 200e9, "g": 77e9, "rho": 7850.0}
                ],
                "elements": [
                    {
                        "id": 1,
                        "start_node": 1,
                        "end_node": 2,
                        "material_id": 1,
                        "area": 0.01,
                        "iy": 8.0e-6,
                        "iz": 8.0e-6,
                        "j": 1.0e-5,
                    }
                ],
                "supports": [{"node_id": 1, **fixed}],
                "loads": [
                    {
                        "node_id": 2,
                        "load_case_id": "service",
                        "fx": 1_000.0,
                        "fz": -100_000.0,
                    }
                ],
                "load_cases": [
                    {"id": "service", "name": "Carga combinada", "kind": "live"}
                ],
                "combination": {
                    "id": "case",
                    "name": "Caso",
                    "kind": "manual",
                    "limit_state": "uls_normal",
                    "situation": "persistent",
                    "factors": {"service": 1.0},
                },
                "solver_engine": "openseespy",
            }
        )
        engine = OpenSeesPyEngine()

        first_order = engine.solve(request)
        second_order = engine.solve(request.model_copy(update={"analysis_order": "second_order"}))

        first_sway = abs(first_order.displacements[-1].ux)
        second_sway = abs(second_order.displacements[-1].ux)
        self.assertGreater(second_sway, first_sway * 1.05)
        self.assertLess(second_sway, first_sway * 2.0)

    def test_member_deflection_removes_rigid_chord_motion(self) -> None:
        element = Element(
            id=1,
            start_node=1,
            end_node=2,
            material_id=1,
            area=0.01,
        )
        runtime = ElementRuntimeInfo(
            element=element,
            material_e=200e9,
            length=4.0,
            x_axis=(1.0, 0.0, 0.0),
            y_axis=(0.0, 1.0, 0.0),
            z_axis=(0.0, 0.0, 1.0),
        )
        theta = 0.01
        result = OpenSeesPyEngine._element_deflection(
            runtime,
            {
                1: NodeDisplacement(node_id=1, ux=0, uy=0, uz=0, rx=0, ry=0, rz=theta, magnitude=0),
                2: NodeDisplacement(node_id=2, ux=0, uy=theta * 4, uz=0, rx=0, ry=0, rz=theta, magnitude=theta * 4),
            },
        )
        self.assertAlmostEqual(result.resultant_max_abs, 0.0, places=12)

    def test_member_deflection_recovers_cubic_midspan_shape(self) -> None:
        element = Element(
            id=1,
            start_node=1,
            end_node=2,
            material_id=1,
            area=0.01,
        )
        runtime = ElementRuntimeInfo(
            element=element,
            material_e=200e9,
            length=4.0,
            x_axis=(1.0, 0.0, 0.0),
            y_axis=(0.0, 1.0, 0.0),
            z_axis=(0.0, 0.0, 1.0),
        )
        result = OpenSeesPyEngine._element_deflection(
            runtime,
            {
                1: NodeDisplacement(node_id=1, ux=0, uy=0, uz=0, rx=0, ry=0, rz=0.01, magnitude=0),
                2: NodeDisplacement(node_id=2, ux=0, uy=0, uz=0, rx=0, ry=0, rz=-0.01, magnitude=0),
            },
        )
        self.assertAlmostEqual(result.local_y_max_abs, 0.01, places=12)
        self.assertAlmostEqual(result.local_y_position, 2.0, places=12)

    def test_linear_model_uses_basis_superposition_and_tracks_envelopes(self) -> None:
        combinations = [
            _combination("uls_a", limit_state="uls_normal", factors={"dead": 1.4, "live": 1.5}),
            _combination("uls_b", limit_state="uls_normal", factors={"dead": 1.0, "live": -1.0}),
        ]
        solver = FakeSolver()
        response = solve_project(_request(combinations), solver)

        self.assertEqual(response.project.strategy, "linear_superposition")
        self.assertEqual(len(solver.calls), 2)
        self.assertEqual({item[0] for item in solver.calls}, {"basis_dead", "basis_live"})
        axial = response.element_envelopes[0].components["axial"]
        self.assertAlmostEqual(axial.minimum, 8_000.0)
        self.assertAlmostEqual(axial.maximum, 14_000.0)
        self.assertEqual(axial.minimum_combination_id, "uls_a")
        self.assertEqual(axial.maximum_combination_id, "uls_b")

    def test_unilateral_member_forces_individual_combination_solution(self) -> None:
        combinations = [
            _combination("uls_a", limit_state="uls_normal", factors={"dead": 1.0}),
            _combination("uls_b", limit_state="uls_normal", factors={"live": 1.0}),
        ]
        solver = FakeSolver()
        response = solve_project(_request(combinations, tension_only=True), solver)

        self.assertEqual(response.project.strategy, "individual")
        self.assertEqual(solver.calls, [("uls_a", "first_order"), ("uls_b", "first_order")])

    def test_member_loading_with_deflection_check_uses_exact_combination_solution(self) -> None:
        combinations = [
            _combination("sls_a", limit_state="sls_rare", factors={"dead": 1.0}),
            _combination("sls_b", limit_state="sls_frequent", factors={"live": 1.0}),
        ]
        request = _request(combinations, deflection_ratio_limit=250)
        request = request.model_copy(
            update={
                "member_distributed_loads": [
                    MemberDistributedLoad(
                        element_id=1,
                        load_case_id="dead",
                        direction="Fz",
                        w1=-1_000.0,
                        w2=-1_000.0,
                        x1=0.0,
                        x2=5.0,
                    )
                ]
            }
        )
        solver = FakeSolver()

        response = solve_project(request, solver)

        self.assertEqual(response.project.strategy, "individual")
        self.assertEqual(solver.calls, [("sls_a", "first_order"), ("sls_b", "first_order")])

    def test_partial_failure_keeps_successes_but_marks_project_incomplete(self) -> None:
        combinations = [
            _combination("uls_ok", limit_state="uls_normal", factors={"dead": 1.0}),
            _combination("uls_bad", limit_state="uls_normal", factors={"live": 1.0}),
        ]
        solver = FakeSolver(fail_ids={"uls_bad"})
        response = solve_project(_request(combinations, tension_only=True), solver)

        self.assertEqual(response.project.status, "incomplete")
        self.assertEqual(response.project.succeeded_combinations, 1)
        self.assertEqual(response.project.failed_combinations, 1)
        self.assertTrue(response.analysis.combination_name.startswith("Projeto incompleto"))
        failures = [item for item in response.combination_results if item.status == "failed"]
        self.assertEqual(len(failures), 1)
        self.assertIn("falha controlada", failures[0].error)

    def test_second_order_compares_reference_and_reports_amplification(self) -> None:
        combinations = [
            _combination("uls_a", limit_state="uls_normal", factors={"dead": 1.0}),
        ]
        solver = FakeSolver()
        response = solve_project(_request(combinations, second_order=True), solver)

        self.assertEqual(
            solver.calls,
            [("uls_a", "first_order"), ("uls_a", "second_order")],
        )
        self.assertAlmostEqual(response.combination_results[0].displacement_amplification, 1.2)
        self.assertEqual(response.project.stability.status, "attention")
        self.assertAlmostEqual(response.project.stability.max_displacement_amplification, 1.2)

    def test_second_order_failure_reports_successful_first_order_reference(self) -> None:
        combinations = [
            _combination("uls_ok", limit_state="uls_normal", factors={"dead": 1.0}),
            _combination("uls_second_order_fails", limit_state="uls_normal", factors={"live": 1.0}),
        ]
        base_solver = FakeSolver()

        def solver(request: SolveRequest) -> SolveResponse:
            if (
                request.combination.id == "uls_second_order_fails"
                and request.analysis_order == "second_order"
            ):
                raise ValueError("equilibrio de segunda ordem indisponivel")
            return base_solver(request)

        response = solve_project(
            _request(combinations, second_order=True),
            solver,
        )

        failure = next(item for item in response.combination_results if item.status == "failed")
        self.assertIn("referencia de primeira ordem convergiu", failure.error)
        self.assertIn("segunda ordem falhou", failure.error)

    def test_serviceability_and_member_design_are_consolidated(self) -> None:
        combinations = [
            _combination("uls_a", limit_state="uls_normal", factors={"dead": 0.1}),
            _combination("sls_a", limit_state="sls_rare", factors={"dead": 1.0}),
        ]
        solver = FakeSolver(deflection_scale=0.003)
        response = solve_project(
            _request(
                combinations,
                verify_profiles=True,
                deflection_ratio_limit=200,
                strategy="individual",
            ),
            solver,
        )

        self.assertEqual(len(response.member_serviceability), 1)
        self.assertEqual(response.member_serviceability[0].status, "failed")
        self.assertAlmostEqual(response.member_serviceability[0].limit_m, 0.025)
        self.assertEqual(len(response.member_design_summaries), 1)
        self.assertEqual(response.member_design_summaries[0].status, "failed")
        self.assertEqual(
            response.member_design_summaries[0].governing_check_id,
            "serviceability-deflection",
        )
        self.assertEqual(len(response.member_design_cases), 1)
        self.assertEqual(response.member_design_cases[0].combination_id, "uls_a")
        self.assertEqual(Counter(item.status for item in response.combination_results), {"succeeded": 2})

        restored = decode_solve_response(encode_solve_response(response))
        self.assertEqual(
            restored.model_dump(mode="json"),
            response.model_dump(mode="json"),
        )

    def test_governing_project_case_accepts_critical_points_beyond_base_401(self) -> None:
        combination = _combination(
            "uls_many_points",
            limit_state="uls_normal",
            factors={"dead": 0.1},
        )
        base_solver = FakeSolver()

        def solver(request: SolveRequest) -> SolveResponse:
            result = base_solver(request)
            start = result.element_diagrams[0].points[0]
            end = result.element_diagrams[0].points[-1]
            points = [
                ElementDiagramPoint(
                    x=5.0 * index / 401.0,
                    axial=start.axial,
                    shear_y=start.shear_y
                    + (end.shear_y - start.shear_y) * index / 401.0,
                    shear_z=0.0,
                    torsion=0.0,
                    moment_y=0.0,
                    moment_z=start.moment_z
                    + (end.moment_z - start.moment_z) * index / 401.0,
                )
                for index in range(402)
            ]
            diagram = result.element_diagrams[0].model_copy(update={"points": points})
            return result.model_copy(update={"element_diagrams": [diagram]})

        response = solve_project(
            _request(
                [combination],
                verify_profiles=True,
                strategy="individual",
            ),
            solver,
        )

        self.assertEqual(response.project.failed_combinations, 0)
        self.assertEqual(len(response.member_design_cases), 1)
        self.assertEqual(len(response.member_design_cases[0].points), 402)

    def test_proven_els_failure_prevails_when_all_uls_results_are_missing(self) -> None:
        combinations = [
            _combination("uls_fails", limit_state="uls_normal", factors={"dead": 0.1}),
            _combination("sls_fails", limit_state="sls_rare", factors={"dead": 1.0}),
        ]
        response = solve_project(
            _request(
                combinations,
                verify_profiles=True,
                deflection_ratio_limit=200,
                strategy="individual",
            ),
            FakeSolver(fail_ids={"uls_fails"}, deflection_scale=0.003),
        )

        summary = response.member_design_summaries[0]
        self.assertEqual(summary.strength_status, "incomplete")
        self.assertEqual(summary.serviceability_status, "failed")
        self.assertEqual(summary.status, "failed")
        self.assertEqual(summary.governing_check_id, "serviceability-deflection")
        self.assertIn("project-uls", summary.incomplete_check_ids)
        self.assertIn("serviceability-deflection", summary.failed_check_ids)

    def test_member_design_rejects_partial_or_ambiguous_solver_results(self) -> None:
        combinations = [
            _combination("uls_ok", limit_state="uls_normal", factors={"dead": 0.2}),
            _combination("uls_bad", limit_state="uls_normal", factors={"live": 0.2}),
        ]

        def mutate_missing_diagram(result: SolveResponse) -> SolveResponse:
            return result.model_copy(update={"element_diagrams": []})

        def mutate_duplicate_force(result: SolveResponse) -> SolveResponse:
            return result.model_copy(
                update={"element_forces": [*result.element_forces, result.element_forces[0]]}
            )

        def mutate_length(result: SolveResponse) -> SolveResponse:
            diagram = result.element_diagrams[0].model_copy(update={"length": 4.0})
            return result.model_copy(update={"element_diagrams": [diagram]})

        def mutate_units(result: SolveResponse) -> SolveResponse:
            analysis = result.analysis.model_copy(
                update={"units": {"length": "m", "force": "kN", "moment": "kN.m"}}
            )
            return result.model_copy(update={"analysis": analysis})

        def mutate_provenance(result: SolveResponse) -> SolveResponse:
            analysis = result.analysis.model_copy(update={"combination_id": "outra"})
            return result.model_copy(update={"analysis": analysis})

        def mutate_endpoint_force(result: SolveResponse) -> SolveResponse:
            force = result.element_forces[0].model_copy(update={"axial_start": 1.0e9})
            return result.model_copy(update={"element_forces": [force]})

        def mutate_three_faces_at_one_position(result: SolveResponse) -> SolveResponse:
            diagram = result.element_diagrams[0]
            faces = [
                diagram.points[0].model_copy(update={"x": 2.5, "shear_z": value})
                for value in (10.0, 20.0, 30.0)
            ]
            return result.model_copy(
                update={
                    "element_diagrams": [
                        diagram.model_copy(
                            update={
                                "points": [
                                    diagram.points[0],
                                    *faces,
                                    diagram.points[-1],
                                ]
                            }
                        )
                    ]
                }
            )

        for mutator in (
            mutate_missing_diagram,
            mutate_duplicate_force,
            mutate_length,
            mutate_units,
            mutate_provenance,
            mutate_endpoint_force,
            mutate_three_faces_at_one_position,
        ):
            with self.subTest(mutator=mutator.__name__):
                base_solver = FakeSolver()

                def solver(request: SolveRequest) -> SolveResponse:
                    result = base_solver(request)
                    if (
                        request.combination.id == "uls_bad"
                        and request.analysis_order == "second_order"
                    ):
                        return mutator(result)
                    return result

                response = solve_project(
                    _request(
                        combinations,
                        second_order=True,
                        verify_profiles=True,
                        strategy="individual",
                    ),
                    solver,
                )

                self.assertEqual(response.project.status, "incomplete")
                self.assertEqual(response.member_design_summaries[0].status, "incomplete")
                self.assertIn(
                    "project-uls",
                    response.member_design_summaries[0].incomplete_check_ids,
                )
                self.assertEqual(
                    response.member_design_summaries[0].governing_check_id,
                    "project-uls",
                )
                self.assertIsNone(response.member_design_summaries[0].governing_utilization)
                self.assertTrue(
                    any(
                        "uls_bad" in issue
                        for issue in response.member_design_summaries[0].input_integrity_issues
                    )
                )
                failed = [item for item in response.combination_results if item.status == "failed"]
                self.assertEqual(len(failed), 1)

    def test_member_design_rejects_element_section_property_divergence(self) -> None:
        combination = _combination(
            "uls_a",
            limit_state="uls_normal",
            factors={"dead": 0.1},
        )
        request = _request(
            [combination],
            verify_profiles=True,
            strategy="individual",
        )
        element = request.elements[0].model_copy(update={"iy": request.elements[0].iy * 0.5})
        request = request.model_copy(update={"elements": [element]})

        response = solve_project(request, FakeSolver())
        summary = response.member_design_summaries[0]

        self.assertEqual(summary.status, "incomplete")
        self.assertIn("project-uls-input", summary.incomplete_check_ids)
        self.assertTrue(any("Iy" in item for item in summary.input_integrity_issues))

    def test_member_design_preserves_pending_check_ids_from_all_uls_cases(self) -> None:
        combinations = [
            _combination("uls_first", limit_state="uls_normal", factors={"dead": 0.1}),
            _combination("uls_torsion", limit_state="uls_normal", factors={"dead": 0.1}),
        ]
        base_solver = FakeSolver()

        def solver(request: SolveRequest) -> SolveResponse:
            result = base_solver(request)
            if request.combination.id != "uls_torsion":
                return result
            diagram = result.element_diagrams[0]
            points = [point.model_copy(update={"torsion": 1.0e3}) for point in diagram.points]
            force = result.element_forces[0].model_copy(
                update={"torsion_start": 1.0e3, "torsion_end": 1.0e3}
            )
            return result.model_copy(
                update={
                    "element_diagrams": [diagram.model_copy(update={"points": points})],
                    "element_forces": [force],
                }
            )

        response = solve_project(
            _request(
                combinations,
                verify_profiles=True,
                strategy="individual",
            ),
            solver,
        )

        summary = response.member_design_summaries[0]
        self.assertEqual(summary.status, "incomplete")
        self.assertIn("moment-shear-scope", summary.incomplete_check_ids)
        self.assertIn("torsion", summary.incomplete_check_ids)

    def test_missing_section_is_incomplete_instead_of_outside_the_module(self) -> None:
        combination = _combination(
            "uls_a",
            limit_state="uls_normal",
            factors={"dead": 0.1},
        )
        request = _request(
            [combination],
            verify_profiles=True,
            strategy="individual",
        )
        element = request.elements[0].model_copy(update={"section_id": None})
        request = request.model_copy(update={"elements": [element]})

        response = solve_project(request, FakeSolver())
        summary = response.member_design_summaries[0]

        self.assertEqual(summary.status, "incomplete")
        self.assertEqual(summary.strength_status, "incomplete")
        self.assertIn("project-uls-input", summary.incomplete_check_ids)
        self.assertTrue(any("secao" in item for item in summary.input_integrity_issues))

    def test_omitted_section_shape_is_missing_input_not_outside_the_module(self) -> None:
        combination = _combination(
            "uls_a",
            limit_state="uls_normal",
            factors={"dead": 0.1},
        )
        request_data = _request(
            [combination],
            verify_profiles=True,
            strategy="individual",
        ).model_dump()
        request_data["sections"][0].pop("shape")
        request = SolveRequest.model_validate(request_data)

        self.assertIsNone(request.sections[0].shape)
        response = solve_project(request, FakeSolver())
        summary = response.member_design_summaries[0]

        self.assertEqual(summary.status, "incomplete")
        self.assertEqual(summary.strength_status, "incomplete")
        self.assertIn("project-uls-input", summary.incomplete_check_ids)
        self.assertTrue(
            any("forma" in item for item in summary.input_integrity_issues)
        )

    def test_missing_project_buckling_factors_are_not_replaced_by_one(self) -> None:
        combination = _combination(
            "uls_a",
            limit_state="uls_normal",
            factors={"dead": 0.1},
        )
        response = solve_project(
            _request(
                [combination],
                verify_profiles=True,
                strategy="individual",
                declare_design_data=False,
            ),
            FakeSolver(),
        )

        self.assertEqual(response.member_design_summaries[0].status, "incomplete")

    def test_incomplete_or_incoherent_sls_deflection_keeps_serviceability_incomplete(self) -> None:
        combinations = [
            _combination("sls_a", limit_state="sls_rare", factors={"dead": 1.0}),
            _combination("sls_b", limit_state="sls_frequent", factors={"live": 1.0}),
        ]
        for mode in ("missing", "incoherent"):
            with self.subTest(mode=mode):
                base_solver = FakeSolver(deflection_scale=0.0001)

                def solver(request: SolveRequest) -> SolveResponse:
                    result = base_solver(request)
                    if request.combination.id != "sls_b":
                        return result
                    if mode == "missing":
                        return result.model_copy(update={"element_deflections": []})
                    deflection = result.element_deflections[0].model_copy(
                        update={"local_y_max_abs": 1.0, "resultant_max_abs": 0.001}
                    )
                    return result.model_copy(update={"element_deflections": [deflection]})

                response = solve_project(
                    _request(
                        combinations,
                        deflection_ratio_limit=250,
                        strategy="individual",
                    ),
                    solver,
                )

                self.assertEqual(response.member_serviceability[0].status, "incomplete")
                self.assertIn("sls_b", response.member_serviceability[0].summary.lower())

    def test_superposition_does_not_wash_invalid_basis_provenance_or_diagrams(self) -> None:
        combinations = [
            _combination("uls_dead", limit_state="uls_normal", factors={"dead": 0.1}),
            _combination("uls_live", limit_state="uls_normal", factors={"live": 0.1}),
        ]
        for mode in ("missing_diagram", "partial_diagram", "wrong_provenance"):
            with self.subTest(mode=mode):
                base_solver = FakeSolver()

                def solver(request: SolveRequest) -> SolveResponse:
                    result = base_solver(request)
                    if request.combination.id != "basis_dead":
                        return result
                    if mode == "missing_diagram":
                        return result.model_copy(update={"element_diagrams": []})
                    if mode == "partial_diagram":
                        points = [
                            result.element_diagrams[0].points[0].model_copy(update={"x": 1.0}),
                            result.element_diagrams[0].points[-1].model_copy(update={"x": 4.0}),
                        ]
                        diagram = result.element_diagrams[0].model_copy(update={"points": points})
                        return result.model_copy(update={"element_diagrams": [diagram]})
                    analysis = result.analysis.model_copy(update={"combination_id": "outra_base"})
                    return result.model_copy(update={"analysis": analysis})

                response = solve_project(
                    _request(combinations, verify_profiles=True),
                    solver,
                )

                self.assertEqual(response.project.status, "incomplete")
                self.assertEqual(response.project.failed_combinations, 1)
                failed = next(item for item in response.combination_results if item.status == "failed")
                self.assertIn("dead", failed.error.lower())

    def test_nonfinite_internal_solver_values_fail_the_combination_conservatively(self) -> None:
        combinations = [
            _combination("uls_ok", limit_state="uls_normal", factors={"dead": 0.1}),
            _combination("uls_bad", limit_state="uls_normal", factors={"dead": 0.2}),
        ]

        for nonfinite in (math.nan, math.inf, -math.inf):
            with self.subTest(nonfinite=nonfinite):
                base_solver = FakeSolver()

                def solver(request: SolveRequest) -> SolveResponse:
                    result = base_solver(request)
                    if request.combination.id != "uls_bad":
                        return result
                    diagram = result.element_diagrams[0]
                    middle = diagram.points[0].model_copy(
                        update={"x": 2.5, "axial": nonfinite}
                    )
                    return result.model_copy(
                        update={
                            "element_diagrams": [
                                diagram.model_copy(
                                    update={
                                        "points": [
                                            diagram.points[0],
                                            middle,
                                            diagram.points[-1],
                                        ]
                                    }
                                )
                            ]
                        }
                    )

                response = solve_project(
                    _request(
                        combinations,
                        verify_profiles=True,
                        strategy="individual",
                    ),
                    solver,
                )

                self.assertEqual(response.project.status, "incomplete")
                self.assertEqual(response.project.succeeded_combinations, 1)
                self.assertEqual(response.project.failed_combinations, 1)
                summary = response.member_design_summaries[0]
                self.assertEqual(summary.status, "incomplete")
                self.assertIn("project-uls", summary.incomplete_check_ids)
                failure = next(
                    item
                    for item in response.combination_results
                    if item.combination_id == "uls_bad"
                )
                self.assertEqual(failure.status, "failed")
                self.assertIn("nao finito", failure.error.lower())

    def test_combination_permutation_keeps_the_same_governing_design_case(self) -> None:
        combinations = [
            _combination("uls_low", limit_state="uls_normal", factors={"dead": 0.05}),
            _combination("uls_high", limit_state="uls_normal", factors={"dead": 0.20}),
        ]
        responses = [
            solve_project(
                _request(
                    ordered,
                    verify_profiles=True,
                    strategy="individual",
                ),
                FakeSolver(),
            )
            for ordered in (combinations, list(reversed(combinations)))
        ]

        first, reversed_order = responses
        for response in responses:
            summary = response.member_design_summaries[0]
            case = response.member_design_cases[0]
            self.assertEqual(response.project.status, "complete")
            self.assertEqual(summary.status, "incomplete")
            self.assertEqual(summary.governing_combination_id, "uls_high")
            self.assertEqual(case.combination_id, "uls_high")
            self.assertEqual(
                response.project.governing_force_combination_id,
                "uls_high",
            )

        self.assertEqual(
            first.project.max_axial_force,
            reversed_order.project.max_axial_force,
        )
        self.assertEqual(
            first.project.max_shear_force,
            reversed_order.project.max_shear_force,
        )
        self.assertEqual(
            first.project.max_bending_moment,
            reversed_order.project.max_bending_moment,
        )
        self.assertEqual(
            first.member_design_summaries[0].model_dump(mode="json"),
            reversed_order.member_design_summaries[0].model_dump(mode="json"),
        )
        self.assertEqual(
            first.member_design_cases[0].model_dump(mode="json"),
            reversed_order.member_design_cases[0].model_dump(mode="json"),
        )

    def test_exact_combination_ties_use_canonical_ids_in_auditable_outputs(self) -> None:
        combinations = [
            _combination("uls_z", limit_state="uls_normal", factors={"dead": 0.10}),
            _combination("uls_a", limit_state="uls_normal", factors={"dead": 0.10}),
        ]
        responses = [
            solve_project(
                _request(
                    ordered,
                    second_order=True,
                    verify_profiles=True,
                    strategy="individual",
                ),
                FakeSolver(),
            )
            for ordered in (combinations, list(reversed(combinations)))
        ]

        for response in responses:
            self.assertEqual(
                response.member_design_summaries[0].governing_combination_id,
                "uls_a",
            )
            self.assertEqual(response.member_design_cases[0].combination_id, "uls_a")
            self.assertEqual(
                response.project.governing_force_combination_id,
                "uls_a",
            )
            self.assertEqual(
                response.project.governing_displacement_combination_id,
                "uls_a",
            )
            self.assertEqual(
                response.project.stability.governing_combination_id,
                "uls_a",
            )
            for component in response.element_envelopes[0].components.values():
                self.assertEqual(component.minimum_combination_id, "uls_a")
                self.assertEqual(component.maximum_combination_id, "uls_a")


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