import asyncio
import base64
import hashlib
import json
import os
import re
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

from fastapi import HTTPException

from app import calculation_routes
import app.main as main_module
from app.main import CONTENT_SECURITY_POLICY, MAX_REQUEST_BODY_BYTES, app
from app.database import init_database
from app.models import User
from app.release_metadata import (
    APP_REVISION,
    APP_TAG,
    APP_VERSION,
    load_release_metadata,
    metadata_from_revision,
)
from app.schemas import ProjectDocument
from app.security import get_admin_user


async def call_asgi(
    method: str,
    path: str,
    body: bytes = b"",
    headers: list[tuple[bytes, bytes]] | None = None,
    scheme: str = "https",
    client: tuple[str, int] = ("127.0.0.1", 12345),
    host: bytes = b"fse3d.engfelix.com.br",
    query_string: bytes = b"",
):
    messages = []
    received = False
    scope = {
        "type": "http",
        "asgi": {"version": "3.0"},
        "http_version": "1.1",
        "method": method,
        "scheme": scheme,
        "path": path,
        "raw_path": path.encode("ascii"),
        "query_string": query_string,
        "headers": [(b"host", host), *(headers or [])],
        "client": client,
        "server": ("fse3d.engfelix.com.br", 443 if scheme == "https" else 80),
    }

    async def receive():
        nonlocal received
        if not received:
            received = True
            return {"type": "http.request", "body": body, "more_body": False}
        return {"type": "http.disconnect"}

    async def send(message):
        messages.append(message)

    await app(scope, receive, send)
    start = next(message for message in messages if message["type"] == "http.response.start")
    response_body = b"".join(
        message.get("body", b"")
        for message in messages
        if message["type"] == "http.response.body"
    )
    return start["status"], dict(start.get("headers", [])), response_body


class ApiContractsTests(unittest.TestCase):
    def test_security_boolean_environment_is_strict(self) -> None:
        parsers = (main_module._env_bool, calculation_routes._env_bool)
        for parser in parsers:
            with self.subTest(parser=parser.__module__):
                with patch.dict(os.environ, {"FSE3D_BOOLEAN_TEST": "tru"}):
                    with self.assertRaisesRegex(RuntimeError, "booleano explicito"):
                        parser("FSE3D_BOOLEAN_TEST", False)
                with patch.dict(os.environ, {"FSE3D_BOOLEAN_TEST": "false"}):
                    self.assertIs(parser("FSE3D_BOOLEAN_TEST", True), False)
                with patch.dict(os.environ, {"FSE3D_BOOLEAN_TEST": "true"}):
                    self.assertIs(parser("FSE3D_BOOLEAN_TEST", False), True)

    def test_r226_is_the_only_canonical_identity(self) -> None:
        root = Path(__file__).resolve().parents[1]

        self.assertEqual(APP_REVISION, "R2.28")
        self.assertEqual(APP_VERSION, "2.28.0")
        self.assertEqual(APP_TAG, "rev-2.28")
        self.assertEqual(
            json.loads((root / "frontend/revision.json").read_text(encoding="utf-8")),
            {"revision": APP_REVISION},
        )

        package = json.loads((root / "package.json").read_text(encoding="utf-8"))
        lock = json.loads((root / "package-lock.json").read_text(encoding="utf-8"))
        self.assertEqual(package["version"], APP_VERSION)
        self.assertEqual(lock["version"], APP_VERSION)
        self.assertEqual(lock["packages"][""]["version"], APP_VERSION)

    def test_invalid_or_ambiguous_revision_fails_closed(self) -> None:
        for invalid in (
            "2.21",
            "R2.1",
            "R2.021",
            "R2.21.0",
            "R02.21",
            "R2.21 ",
            "R2.100",
            "R0.01",
        ):
            with self.subTest(invalid=invalid):
                with self.assertRaises(ValueError):
                    metadata_from_revision(invalid)

        with tempfile.TemporaryDirectory() as directory:
            path = Path(directory) / "revision.json"
            path.write_text(
                json.dumps({"revision": "R2.21", "version": "9.9.9"}),
                encoding="utf-8",
            )
            with self.assertRaises(RuntimeError):
                load_release_metadata(path)

    def test_fastapi_and_openapi_expose_the_canonical_semver(self) -> None:
        self.assertEqual(app.version, APP_VERSION)
        self.assertEqual(app.openapi()["info"]["version"], APP_VERSION)

    def test_generated_frontend_and_map_are_current(self) -> None:
        root = Path(__file__).resolve().parents[1]
        app_js = (root / "app/static/app.js").read_text(encoding="utf-8")
        admin_html = (root / "app/static/administracao/index.html").read_text(
            encoding="utf-8"
        )
        map_payload = json.loads(
            (root / "app/static/mapadoprojeto/map-data.json").read_text(
                encoding="utf-8"
            )
        )

        self.assertIn(f'const APP_REVISION = "{APP_REVISION}";', app_js)
        self.assertIn(f'class="revision">{APP_REVISION}</span>', admin_html)
        self.assertEqual(map_payload["meta"]["revision"], APP_REVISION)

    def test_load_combination_generation_endpoint_requires_csrf_and_returns_families(self) -> None:
        payload = json.dumps(
            {
                "load_cases": [
                    {"id": "g", "name": "G", "kind": "dead"},
                    {"id": "q", "name": "Q", "kind": "live"},
                ],
                "used_case_ids": ["g", "q"],
            }
        ).encode("utf-8")
        base_headers = [
            (b"content-type", b"application/json"),
            (b"content-length", str(len(payload)).encode("ascii")),
        ]

        status, _, _ = asyncio.run(
            call_asgi(
                "POST",
                "/api/load-combinations/generate",
                body=payload,
                headers=base_headers,
            )
        )
        self.assertEqual(status, 403)

        status, _, body = asyncio.run(
            call_asgi(
                "POST",
                "/api/load-combinations/generate",
                body=payload,
                headers=[
                    *base_headers,
                    (b"cookie", b"fse3d_csrf=test-csrf-token"),
                    (b"x-fse3d-csrf", b"test-csrf-token"),
                ],
            )
        )
        self.assertEqual(status, 200)
        response = json.loads(body)
        self.assertEqual(response["stats"]["active_case_count"], 2)
        self.assertGreater(response["stats"]["generated_count"], 0)
        self.assertEqual(
            set(response["stats"]["counts_by_limit_state"]),
            {"uls_normal", "sls_rare", "sls_frequent", "sls_quasi_permanent"},
        )
        self.assertTrue(response["complete"])
        self.assertEqual(response["blocking_issues"], [])
        self.assertEqual(
            {item["limit_state"] for item in response["families"]},
            {"uls_normal", "sls_rare", "sls_frequent", "sls_quasi_permanent"},
        )

    def test_load_combination_generation_rejects_factor_product_before_handler(self) -> None:
        payload = json.dumps(
            {
                "load_cases": [
                    {"id": "g", "name": "G", "kind": "dead"},
                    {
                        "id": "q",
                        "name": "Q",
                        "kind": "live",
                        "gamma_uls_unfavorable": 100.0,
                        "psi0": 2.0,
                    },
                ],
                "used_case_ids": ["g", "q"],
                "settings": {"limit_states": ["uls_normal"]},
            }
        ).encode("utf-8")
        status, _, body = asyncio.run(
            call_asgi(
                "POST",
                "/api/load-combinations/generate",
                body=payload,
                headers=[
                    (b"content-type", b"application/json"),
                    (b"content-length", str(len(payload)).encode("ascii")),
                    (b"cookie", b"fse3d_csrf=test-csrf-token"),
                    (b"x-fse3d-csrf", b"test-csrf-token"),
                ],
            )
        )

        self.assertEqual(status, 422)
        self.assertIn(b"gamma_uls_unfavorable * psi0", body)

    def test_versioned_static_asset_is_served_with_immutable_cache(self) -> None:
        status, headers, body = asyncio.run(
            call_asgi(
                "GET",
                "/static/styles.css",
                query_string=b"v=R1.53",
            )
        )
        self.assertEqual(status, 200)
        self.assertIn(b":root", body)
        self.assertEqual(
            headers[b"cache-control"],
            b"public, max-age=31536000, immutable",
        )
        self.assertNotIn(b"pragma", headers)
        self.assertNotIn(b"expires", headers)

    def test_importmap_hash_matches_content_security_policy(self) -> None:
        html = Path("app/static/index.html").read_text(encoding="utf-8")
        match = re.search(r'<script\s+type="importmap">(.*?)</script>', html, re.DOTALL)
        self.assertIsNotNone(match)
        digest = base64.b64encode(
            hashlib.sha256(match.group(1).encode("utf-8")).digest()
        ).decode("ascii")
        self.assertIn(f"'sha256-{digest}'", CONTENT_SECURITY_POLICY)

    def test_allowed_host_supports_explicit_wildcards(self) -> None:
        from unittest.mock import patch

        from app import main

        with patch.object(main, "ALLOWED_HOSTS", ["*.example.com"]):
            self.assertTrue(main._host_is_allowed("app.example.com"))
            self.assertFalse(main._host_is_allowed("example.com.attacker.test"))

    def test_project_report_route_serves_executive_dashboard(self) -> None:
        status, headers, body = asyncio.run(call_asgi("GET", "/projeto"))
        self.assertEqual(status, 200)
        self.assertIn(b"Cronograma previsto", body)
        self.assertIn(b"Avan\xc3\xa7o real e cronograma de 12 meses", body)
        self.assertIn(b"Motor OpenSees", body)
        self.assertIn(b"100%", body)
        self.assertIn(b"Biblioteca de perfis", body)
        self.assertIn(b"no-store", headers[b"cache-control"])
        self.assertIn(b"content-security-policy", headers)

    def test_project_map_route_serves_audited_visual_architecture(self) -> None:
        init_database()
        protected_paths = (
            "/mapadoprojeto",
            "/mapadoprojeto/",
            "/static/mapadoprojeto/index.html",
            "/static/mapadoprojeto/map-data.json",
            "/static/mapadoprojeto/mapadoprojeto.css",
            "/static/mapadoprojeto/mapadoprojeto.js",
        )
        for route in protected_paths:
            status, headers, _ = asyncio.run(call_asgi("GET", route))
            self.assertEqual(status, 401, route)
            self.assertIn(b"no-store", headers[b"cache-control"])

        def ordinary_user_denied() -> User:
            raise HTTPException(status_code=403, detail="Acesso restrito a administradores.")

        app.dependency_overrides[get_admin_user] = ordinary_user_denied
        try:
            for route in protected_paths:
                status, _, _ = asyncio.run(call_asgi("GET", route))
                self.assertEqual(status, 403, route)
        finally:
            app.dependency_overrides.pop(get_admin_user, None)

    def test_admin_panel_and_assets_require_administrator_role(self) -> None:
        init_database()
        protected_paths = (
            "/administracao",
            "/administracao/",
            "/static/administracao/index.html",
            "/static/administracao/administracao.css",
            "/static/administracao/administracao.js",
        )
        for route in protected_paths:
            status, headers, _ = asyncio.run(call_asgi("GET", route))
            self.assertEqual(status, 401, route)
            self.assertIn(b"no-store", headers[b"cache-control"])

        def ordinary_user_denied() -> User:
            raise HTTPException(status_code=403, detail="Acesso restrito a administradores.")

        app.dependency_overrides[get_admin_user] = ordinary_user_denied
        try:
            for route in protected_paths:
                status, _, _ = asyncio.run(call_asgi("GET", route))
                self.assertEqual(status, 403, route)
        finally:
            app.dependency_overrides.pop(get_admin_user, None)

        admin = User(
            id=998,
            account_uid="FSE-ADMIN-PAINEL",
            name="Administrador",
            email="admin-panel@example.com",
            password_hash="not-used",
            is_active=True,
            is_admin=True,
        )
        app.dependency_overrides[get_admin_user] = lambda: admin
        try:
            status, headers, body = asyncio.run(call_asgi("GET", "/administracao"))
            self.assertEqual(status, 200)
            self.assertIn("Administração do sistema".encode("utf-8"), body)
            self.assertIn(b"/static/administracao/administracao.js", body)
            self.assertIn(b"no-store", headers[b"cache-control"])

            for asset in (
                "/static/administracao/administracao.css",
                "/static/administracao/administracao.js",
            ):
                status, headers, body = asyncio.run(
                    call_asgi("GET", asset, query_string=b"v=R2.17")
                )
                self.assertEqual(status, 200, asset)
                self.assertTrue(body, asset)
                self.assertIn(b"private", headers[b"cache-control"])
                self.assertIn(b"no-store", headers[b"cache-control"])

            status, _, body = asyncio.run(call_asgi("GET", "/api/admin/summary"))
            self.assertEqual(status, 200)
            summary = json.loads(body)
            self.assertIn("administrators", summary)
            self.assertIn("active_sessions", summary)
        finally:
            app.dependency_overrides.pop(get_admin_user, None)

        admin = User(
            id=999,
            account_uid="FSE-ADMIN-TESTE",
            name="Administrador",
            email="admin@example.com",
            password_hash="not-used",
            is_active=True,
            is_admin=True,
        )
        app.dependency_overrides[get_admin_user] = lambda: admin
        try:
            for route in ("/mapadoprojeto", "/mapadoprojeto/"):
                status, headers, body = asyncio.run(call_asgi("GET", route))
                self.assertEqual(status, 200)
                self.assertIn("Do primeiro nó ao resultado estrutural".encode("utf-8"), body)
                self.assertIn("O que sabemos, e até onde sabemos".encode("utf-8"), body)
                self.assertIn("Nenhum domínio fica fora do mapa".encode("utf-8"), body)
                self.assertIn(b"/static/mapadoprojeto/mapadoprojeto.js", body)
                self.assertIn(b"no-store", headers[b"cache-control"])
                self.assertIn(b"content-security-policy", headers)

            status, headers, body = asyncio.run(
                call_asgi(
                    "GET",
                    "/static/mapadoprojeto/map-data.json",
                    query_string=b"v=R2.15",
                )
            )
            self.assertEqual(status, 200)
            self.assertIn(b'"schemaVersion"', body)
            self.assertIn(b"private", headers[b"cache-control"])
            self.assertIn(b"no-store", headers[b"cache-control"])
            self.assertEqual(headers[b"vary"], b"Cookie")

            status, _, _ = asyncio.run(
                call_asgi("GET", "/static/mapadoprojeto/nao-existe.txt")
            )
            self.assertEqual(status, 404)
        finally:
            app.dependency_overrides.pop(get_admin_user, None)

    def test_user_manual_documents_history_reset_without_native_confirmation(self) -> None:
        status, headers, body = asyncio.run(call_asgi("GET", "/manual"))
        self.assertEqual(status, 200)
        self.assertIn("Manual de uso".encode("utf-8"), body)
        self.assertIn("Um cálculo concluído reinicia o histórico".encode("utf-8"), body)
        self.assertIn("sem confirmação do navegador".encode("utf-8"), body)
        self.assertIn("não funciona em smartphones".encode("utf-8"), body)
        self.assertIn(b"no-store", headers[b"cache-control"])
        self.assertIn(b"content-security-policy", headers)

    def test_health_config_and_demo_contracts(self) -> None:
        status, _, body = asyncio.run(call_asgi("GET", "/api/health"))
        self.assertEqual(status, 200)
        health = json.loads(body)
        self.assertEqual(health["status"], "ok")
        self.assertEqual(health["checks"], {"database": True, "openseespy": True})

        status, headers, body = asyncio.run(call_asgi("GET", "/api/config"))
        self.assertEqual(status, 200)
        config = json.loads(body)
        self.assertEqual(config["revision"], APP_REVISION)
        self.assertEqual(config["version"], APP_VERSION)
        self.assertIn("auth_required", config)
        self.assertIn("docs_enabled", config)
        self.assertIn("max_solve_nodes", config)
        self.assertIn("max_solve_elements", config)
        self.assertIn("max_solve_load_items", config)
        self.assertIn("max_stiffness_dof", config)
        self.assertIn("max_solve_work_units", config)
        self.assertIn("max_sync_solve_request_body_bytes", config)
        self.assertIn("solve_timeout_seconds", config)
        self.assertIn("solve_max_concurrent", config)
        self.assertTrue(config["calculation_jobs_enabled"])
        self.assertIn("max_job_nodes", config)
        self.assertIn("max_job_elements", config)
        self.assertIn("max_active_jobs_per_user", config)
        self.assertEqual(
            {item["id"]: item["status"] for item in config["solver_engines"]},
            {"openseespy": "available", "pynite": "future", "native_truss": "future"},
        )
        self.assertEqual(
            {item["id"]: item["status"] for item in config["analysis_modes"]}["nbr_8681_2025"],
            "available",
        )
        self.assertIn(b"set-cookie", headers)
        self.assertIn(b"content-security-policy", headers)
        self.assertIn(b"x-frame-options", headers)
        self.assertIn(b"x-content-type-options", headers)
        self.assertEqual(headers[b"cross-origin-opener-policy"], b"same-origin")
        self.assertEqual(headers[b"cross-origin-resource-policy"], b"same-origin")
        self.assertEqual(headers[b"x-frame-options"], b"DENY")
        self.assertEqual(headers[b"x-content-type-options"], b"nosniff")

        status, _, _ = asyncio.run(call_asgi("GET", "/docs"))
        self.assertEqual(status, 404)

        status, _, _ = asyncio.run(call_asgi("GET", "/openapi.json"))
        self.assertEqual(status, 404)

        status, _, body = asyncio.run(call_asgi("GET", "/api/demo"))
        self.assertEqual(status, 200)
        demo = json.loads(body)
        self.assertEqual(demo["id"], "demo-01")
        self.assertEqual(len(demo["nodes"]), 4)
        self.assertEqual(len(demo["elements"]), 3)
        self.assertEqual(len(demo["sections"]), 1)
        self.assertIn("self_weight", {load_case["id"] for load_case in demo["load_cases"]})
        self.assertIn("permanent", {load_case["id"] for load_case in demo["load_cases"]})
        self.assertGreater(demo["sections"][0]["iy"], demo["sections"][0]["iz"])
        self.assertEqual(demo["sections"][0]["manufacturing_process"], "hot_rolled")
        self.assertEqual(demo["sections"][0]["source_revision"], "11/2018")
        self.assertEqual(demo["sections"][0]["depth_m"], 0.148)
        self.assertEqual(demo["sections"][0]["flange_width_m"], 0.100)
        self.assertEqual(demo["sections"][0]["web_thickness_m"], 0.0043)
        self.assertEqual(demo["sections"][0]["flange_thickness_m"], 0.0049)
        self.assertEqual(demo["sections"][0]["warping_constant_m6"], 4.181e-9)
        self.assertEqual(demo["materials"][0]["grade"], "ASTM A572 Grau 50")
        self.assertEqual(demo["materials"][0]["e"], 200e9)
        self.assertEqual(demo["materials"][0]["g"], 77e9)
        self.assertEqual(demo["materials"][0]["fy"], 345e6)
        self.assertEqual(demo["materials"][0]["fu"], 450e6)
        self.assertEqual({element["section_id"] for element in demo["elements"]}, {1})
        self.assertEqual(demo["elements"][0]["rotation_deg"], 90.0)
        self.assertEqual(demo["elements"][1]["rotation_deg"], 90.0)
        self.assertEqual({layer["name"] for layer in demo["layers"]}, {"PILAR", "VIGA"})
        self.assertIn("layers", demo["elements"][0])

        status, _, body = asyncio.run(call_asgi("GET", "/api/demos"))
        self.assertEqual(status, 200)
        demos = json.loads(body)
        self.assertEqual(demos[0]["id"], "demo-01")
        self.assertIn("demo-02", {item["id"] for item in demos})
        self.assertIn("demo-03", {item["id"] for item in demos})
        self.assertIn("demo-04", {item["id"] for item in demos})
        self.assertIn("demo-05", {item["id"] for item in demos})

        status, _, body = asyncio.run(call_asgi("GET", "/api/demos/demo-01"))
        self.assertEqual(status, 200)
        demo_by_id = json.loads(body)
        self.assertEqual(demo_by_id["elements"][2]["layers"], ["VIGA"])

        status, _, body = asyncio.run(call_asgi("GET", "/api/demos/demo-02"))
        self.assertEqual(status, 200)
        demo_02 = json.loads(body)
        self.assertEqual(len(demo_02["nodes"]), 8)
        self.assertEqual(len(demo_02["elements"]), 8)
        self.assertEqual(len(demo_02["supports"]), 4)
        self.assertIn("live", {load_case["id"] for load_case in demo_02["load_cases"]})
        for element in demo_02["elements"]:
            self.assertEqual(element["section_id"], 1)
            self.assertEqual(element["section_name"], "W 150 x 13,0")
            self.assertGreater(element["area"], 0)
            self.assertGreater(element["iy"], 0)
            self.assertGreater(element["iz"], 0)
            self.assertGreater(element["j"], 0)
        self.assertEqual(
            {element["rotation_deg"] for element in demo_02["elements"] if "PILAR" in element["layers"]},
            {0.0},
        )
        self.assertEqual(
            {element["rotation_deg"] for element in demo_02["elements"] if "VIGA" in element["layers"]},
            {0.0},
        )
        self.assertEqual(
            sum(1 for element in demo_02["elements"] if "VIGA" in element["layers"]),
            4,
        )

        status, _, body = asyncio.run(call_asgi("GET", "/api/demos/demo-03"))
        self.assertEqual(status, 200)
        demo_03 = json.loads(body)
        self.assertEqual(len(demo_03["nodes"]), 74)
        self.assertEqual(len(demo_03["elements"]), 145)
        self.assertEqual(len(demo_03["sections"]), 1)
        self.assertEqual(demo_03["sections"][0]["name"], "W 150 x 13,0")
        self.assertEqual({element["section_id"] for element in demo_03["elements"]}, {1})
        self.assertEqual({element["rotation_deg"] for element in demo_03["elements"]}, {0.0})
        self.assertEqual(len(demo_03["supports"]), 2)
        self.assertEqual(len(demo_03["load_groups"]), 2)
        self.assertEqual({load_group["direction"] for load_group in demo_03["load_groups"]}, {"FZ"})

        status, _, body = asyncio.run(call_asgi("GET", "/api/demos/demo-04"))
        self.assertEqual(status, 200)
        demo_04 = json.loads(body)
        self.assertEqual(len(demo_04["nodes"]), 1324)
        self.assertEqual(len(demo_04["elements"]), 2565)
        self.assertEqual(len(demo_04["supports"]), 34)
        self.assertEqual(len(demo_04["sections"]), 1)
        self.assertEqual(demo_04["sections"][0]["name"], "W 150 x 13,0")
        self.assertEqual({element["section_id"] for element in demo_04["elements"]}, {1})
        self.assertEqual(len(demo_04["loads"]), 0)
        self.assertEqual(len(demo_04["member_point_loads"]), 0)
        self.assertEqual(len(demo_04["member_distributed_loads"]), 0)
        self.assertEqual(len(demo_04["load_groups"]), 2)
        self.assertEqual(len(demo_04["load_panels"]), 0)
        self.assertEqual(len(demo_04["load_cases"]), 5)
        self.assertEqual(len(demo_04["load_action_groups"]), 2)
        self.assertEqual(len(demo_04["load_combinations"]), 4)
        self.assertEqual(len(demo_04["layers"]), 9)
        demo_04_braces = [
            element
            for element in demo_04["elements"]
            if {"CVH", "CVV"}.intersection(element.get("layers") or [])
        ]
        self.assertEqual(len(demo_04_braces), 151)
        self.assertTrue(all(element["tension_only"] for element in demo_04_braces))
        self.assertTrue(all(
            element["start_release_ry"]
            and element["start_release_rz"]
            and element["end_release_ry"]
            and element["end_release_rz"]
            for element in demo_04_braces
        ))
        adjacency = {node["id"]: set() for node in demo_04["nodes"]}
        for element in demo_04["elements"]:
            adjacency[element["start_node"]].add(element["end_node"])
            adjacency[element["end_node"]].add(element["start_node"])
        self.assertFalse([node_id for node_id, neighbors in adjacency.items() if not neighbors])
        visited = set()
        pending = [demo_04["nodes"][0]["id"]]
        while pending:
            node_id = pending.pop()
            if node_id in visited:
                continue
            visited.add(node_id)
            pending.extend(adjacency[node_id] - visited)
        self.assertEqual(len(visited), len(demo_04["nodes"]))
        self.assertIn(
            demo_04["active_combination_id"],
            {combination["id"] for combination in demo_04["load_combinations"]},
        )
        demo_04_nodes = {node["id"]: node for node in demo_04["nodes"]}
        support_node_ids = {support["node_id"] for support in demo_04["supports"]}
        support_nodes = [demo_04_nodes[support["node_id"]] for support in demo_04["supports"]]
        support_columns = []
        for element in demo_04["elements"]:
            if not ({element["start_node"], element["end_node"]} & support_node_ids):
                continue
            start = demo_04_nodes[element["start_node"]]
            end = demo_04_nodes[element["end_node"]]
            if (
                abs(start["x"] - end["x"]) <= 1.0e-9
                and abs(start["y"] - end["y"]) <= 1.0e-9
                and abs(start["z"] - end["z"]) > 1.0
            ):
                support_columns.append(element)
        self.assertEqual(len(support_columns), 34)
        self.assertEqual({element["rotation_deg"] for element in support_columns}, {90.0})
        self.assertEqual({element["mass_kg_m"] for element in demo_04["elements"]}, {13.0})
        self.assertEqual(
            {round(node["x"], 9) for node in support_nodes},
            {float(value) for value in range(0, 31, 6)},
        )
        self.assertEqual({round(node["z"], 9) for node in support_nodes}, {-6.0})
        self.assertEqual(
            sorted({round(node["y"], 9) for node in support_nodes}),
            [float(value) for value in range(0, 73, 6)],
        )
        self.assertTrue(
            all(
                round(node["x"], 9) in {0.0, 30.0}
                or round(node["y"], 9) in {0.0, 72.0}
                for node in support_nodes
            )
        )
        self.assertEqual(
            (
                round(min(node["x"] for node in demo_04["nodes"]), 9),
                round(max(node["x"] for node in demo_04["nodes"]), 9),
                round(min(node["y"] for node in demo_04["nodes"]), 9),
                round(max(node["y"] for node in demo_04["nodes"]), 9),
            ),
            (0.0, 30.0, 0.0, 72.0),
        )

    def test_light_bot_guard_keeps_app_public_but_filters_scanners(self) -> None:
        status, _, body = asyncio.run(call_asgi("GET", "/robots.txt"))
        self.assertEqual(status, 200)
        self.assertIn(b"Disallow: /api/", body)

        status, _, _ = asyncio.run(call_asgi("GET", "/"))
        self.assertEqual(status, 200)

        status, _, _ = asyncio.run(call_asgi(
            "GET",
            "/",
            headers=[(b"user-agent", b"Mozilla/5.0 (compatible; CensysInspect/1.1)")],
            client=("203.0.113.10", 54321),
        ))
        self.assertEqual(status, 403)

        status, _, _ = asyncio.run(call_asgi(
            "GET",
            "/",
            headers=[
                (b"user-agent", b"Mozilla/5.0 (compatible; CensysInspect/1.1)"),
                (b"x-forwarded-for", b"127.0.0.1, 203.0.113.10"),
            ],
            client=("127.0.0.1", 54321),
        ))
        self.assertEqual(status, 403)

        status, _, _ = asyncio.run(call_asgi("GET", "/wp-login.php"))
        self.assertEqual(status, 404)

        status, _, _ = asyncio.run(call_asgi("GET", "/api/demos"))
        self.assertEqual(status, 200)

    def test_forwarded_proto_is_trusted_only_from_configured_proxy(self) -> None:
        status, headers, _ = asyncio.run(
            call_asgi(
                "GET",
                "/api/health",
                headers=[(b"x-forwarded-proto", b"https")],
                scheme="http",
                client=("203.0.113.10", 54321),
            )
        )
        self.assertEqual(status, 308)
        self.assertEqual(headers[b"location"], b"https://fse3d.engfelix.com.br/api/health")
        self.assertIn(b"x-frame-options", headers)

        status, _, body = asyncio.run(
            call_asgi(
                "GET",
                "/api/health",
                headers=[(b"x-forwarded-proto", b"https")],
                scheme="http",
                client=("127.0.0.1", 54321),
            )
        )
        self.assertEqual(status, 200)
        self.assertEqual(json.loads(body)["status"], "ok")

    def test_invalid_host_and_oversized_content_length_are_rejected_early(self) -> None:
        status, headers, _ = asyncio.run(
            call_asgi("GET", "/api/health", host=b"attacker.example")
        )
        self.assertEqual(status, 400)
        self.assertNotIn(b"location", headers)

        status, _, body = asyncio.run(
            call_asgi(
                "POST",
                "/api/solve",
                headers=[(b"content-length", str(MAX_REQUEST_BODY_BYTES + 1).encode("ascii"))],
            )
        )
        self.assertEqual(status, 413)
        self.assertIn(b"too large", body.lower())

    def test_validation_errors_do_not_echo_passwords_or_raw_input(self) -> None:
        secret = "SENHA-QUE-NAO-PODE-VOLTAR"
        status, _, body = asyncio.run(
            call_asgi(
                "POST",
                "/api/auth/register",
                body=json.dumps(
                    {"name": "X", "email": "invalido", "password": secret}
                ).encode("utf-8"),
                headers=[(b"content-type", b"application/json")],
            )
        )
        self.assertEqual(status, 422)
        self.assertNotIn(secret.encode("utf-8"), body)
        errors = json.loads(body)["detail"]
        self.assertTrue(errors)
        self.assertTrue(all(set(error) <= {"type", "loc", "msg"} for error in errors))

    def test_validation_error_response_is_bounded(self) -> None:
        payload = json.dumps(
            {
                "nodes": [{} for _ in range(250)],
                "materials": [],
                "elements": [],
            }
        ).encode("utf-8")
        status, _, body = asyncio.run(
            call_asgi(
                "POST",
                "/api/solve",
                body=payload,
                headers=[(b"content-type", b"application/json")],
            )
        )
        self.assertEqual(status, 422)
        errors = json.loads(body)["detail"]
        self.assertEqual(len(errors), 201)
        self.assertEqual(errors[-1]["type"], "too_many_validation_errors")

    def test_solve_rejects_oversized_models_before_running_solver(self) -> None:
        payload = {
            "nodes": [
                {"id": index, "x": float(index), "y": 0.0, "z": 0.0}
                for index in range(1, 502)
            ],
            "materials": [{"id": 1, "name": "Aco", "e": 210e9}],
            "elements": [
                {
                    "id": 1,
                    "start_node": 1,
                    "end_node": 2,
                    "material_id": 1,
                    "area": 0.01,
                }
            ],
            "supports": [{"node_id": 1, "ux": {"mode": "fixed"}, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}}],
            "loads": [],
        }
        status, _, body = asyncio.run(
            call_asgi(
                "POST",
                "/api/solve",
                body=json.dumps(payload).encode("utf-8"),
                headers=[(b"content-type", b"application/json")],
            )
        )
        self.assertEqual(status, 413)
        self.assertIn("limite 500", json.loads(body)["detail"])

    def test_solve_rejects_models_above_safe_work_budget(self) -> None:
        payload = {
            "nodes": [
                {"id": index, "x": float(index), "y": 0.0, "z": 0.0}
                for index in range(1, 377)
            ],
            "materials": [{"id": 1, "name": "Aco", "e": 210e9}],
            "elements": [
                {
                    "id": index,
                    "start_node": index,
                    "end_node": index + 1,
                    "material_id": 1,
                    "area": 0.01,
                }
                for index in range(1, 376)
            ],
            "supports": [{"node_id": 1, "ux": {"mode": "fixed"}, "uy": {"mode": "fixed"}, "uz": {"mode": "fixed"}}],
            "loads": [],
            "solver_engine": "openseespy",
            "diagram_points": 401,
        }
        status, _, body = asyncio.run(
            call_asgi(
                "POST",
                "/api/solve",
                body=json.dumps(payload).encode("utf-8"),
                headers=[(b"content-type", b"application/json")],
            )
        )
        self.assertEqual(status, 413)
        self.assertIn("orcamento seguro", json.loads(body)["detail"])

    def test_future_solver_returns_explicit_unavailable_message(self) -> None:
        payload = {
            "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", "e": 210e9}],
            "elements": [
                {"id": 1, "start_node": 1, "end_node": 2, "material_id": 1, "area": 0.01}
            ],
            "solver_engine": "native_truss",
        }
        status, _, body = asyncio.run(
            call_asgi(
                "POST",
                "/api/solve",
                body=json.dumps(payload).encode("utf-8"),
                headers=[(b"content-type", b"application/json")],
            )
        )
        self.assertEqual(status, 400)
        self.assertIn("fase futura", json.loads(body)["detail"])

    def test_project_document_accepts_reusable_sections(self) -> None:
        document = ProjectDocument.model_validate(
            {
                "format": "fse.project",
                "format_version": 2,
                "metadata": {"name": "Teste secoes"},
                "model": {
                    "nodes": [],
                    "materials": [],
                    "sections": [
                        {
                            "id": 1,
                            "name": "W12x26",
                            "source": "aisc_w_v16",
                            "shape": "wide_flange_i",
                            "profile_id": "W12X26",
                            "profile_catalog": "aisc_w",
                            "profile_label": "W12x26",
                            "mass_kg_m": 38.7,
                            "area": 0.0004,
                            "iy": 1e-8,
                            "iz": 1e-8,
                            "j": 2e-8,
                        }
                    ],
                    "elements": [
                        {
                            "id": 1,
                            "start_node": 1,
                            "end_node": 2,
                            "material_id": 1,
                            "section_id": 1,
                            "area": 0.0004,
                            "iy": 1e-8,
                            "iz": 1e-8,
                            "j": 2e-8,
                            "start_release_ry": True,
                            "end_release_rz": True,
                            "buckling_ky": 1.2,
                        }
                    ],
                    "loads": [
                        {
                            "node_id": 1,
                            "load_case_id": "live",
                            "visible": False,
                            "gamma": 1.5,
                            "qc0": 0.7,
                            "qc1": 0.6,
                            "qc2": 0.4,
                            "fz": -1000,
                        }
                    ],
                    "member_point_loads": [
                        {
                            "element_id": 1,
                            "load_case_id": "live",
                            "visible": True,
                            "gamma": 1.5,
                            "qc0": 0.7,
                            "qc1": 0.6,
                            "qc2": 0.4,
                            "direction": "FZ",
                            "value": -500,
                            "x": 0.5,
                            "x_ratio": 0.5,
                        }
                    ],
                    "member_distributed_loads": [
                        {
                            "element_id": 1,
                            "load_case_id": "permanent",
                            "visible": True,
                            "gamma": 1.4,
                            "qc0": 1.0,
                            "qc1": 1.0,
                            "qc2": 1.0,
                            "direction": "FZ",
                            "w1": -1000,
                            "w2": -500,
                            "x1": 0.0,
                            "x2": 1.0,
                            "x1_ratio": 0.0,
                            "x2_ratio": 1.0,
                        }
                    ],
                    "load_groups": [
                        {
                            "id": "carga_permanente_1",
                            "load_case_id": "permanent",
                            "style": "distributed",
                            "target_type": "member",
                            "direction": "FZ",
                            "value": -10000,
                            "w2": -10000,
                            "x1_ratio": 0.0,
                            "x2_ratio": 1.0,
                            "visible": True,
                            "gamma": 1.4,
                            "qc0": 1.0,
                            "qc1": 1.0,
                            "qc2": 1.0,
                            "element_ids": [1],
                        }
                    ],
                },
            }
        )

        self.assertEqual(document.model.sections[0].name, "W12x26")
        self.assertEqual(document.model.sections[0].profile_id, "W12X26")
        self.assertEqual(document.model.sections[0].mass_kg_m, 38.7)
        self.assertEqual(document.model.elements[0].section_id, 1)
        self.assertTrue(document.model.elements[0].start_release_ry)
        self.assertTrue(document.model.elements[0].end_release_rz)
        self.assertEqual(document.model.elements[0].buckling_ky, 1.2)
        self.assertFalse(document.model.loads[0].visible)
        self.assertEqual(document.model.loads[0].qc0, 0.7)
        self.assertEqual(document.model.member_point_loads[0].x_ratio, 0.5)
        self.assertEqual(document.model.member_distributed_loads[0].x2_ratio, 1.0)
        self.assertEqual(document.model.load_groups[0].element_ids, [1])
        self.assertEqual(document.model.load_groups[0].style, "distributed")

    def test_section_profiles_are_served_from_database(self) -> None:
        init_database()

        status, _, body = asyncio.run(call_asgi("GET", "/api/section-profiles/hierarchy"))
        self.assertEqual(status, 200)
        hierarchy = json.loads(body)
        self.assertEqual(hierarchy["processes"][0]["id"], "hot_rolled")
        self.assertEqual(hierarchy["families"][0]["id"], "w")
        self.assertEqual(hierarchy["series"][0]["id"], "i")

        status, _, body = asyncio.run(call_asgi("GET", "/api/section-profiles"))
        self.assertEqual(status, 200)
        profiles = json.loads(body)
        self.assertGreaterEqual(len(profiles), 60)
        self.assertIn("W 150 x 13,0", {profile["label"] for profile in profiles})
        first = profiles[0]
        self.assertEqual(first["manufacturing_process"], "hot_rolled")
        self.assertEqual(first["family"], "w")
        self.assertEqual(first["series"], "i")
        self.assertGreater(first["area_m2"], 0)
        self.assertGreater(first["ix_m4"], 0)
        self.assertGreater(first["area_mm2"], 0)
        self.assertGreater(first["ix_mm4"], 0)
        self.assertAlmostEqual(first["area_m2"], first["area_mm2"] * 1e-6, places=12)
        self.assertAlmostEqual(first["ix_m4"], first["ix_mm4"] * 1e-12, places=18)

    def test_section_profile_migration_and_deploy_seed_contracts(self) -> None:
        root = Path(__file__).resolve().parents[1]
        migration = (root / "migrations/versions/0003_section_profiles.py").read_text(encoding="utf-8")
        calculation_migration = (root / "migrations/versions/0004_calculation_jobs.py").read_text(
            encoding="utf-8"
        )
        admin_migration = (root / "migrations/versions/0006_user_admin_role.py").read_text(
            encoding="utf-8"
        )
        admin_audit_migration = (
            root / "migrations/versions/0007_admin_audit_events.py"
        ).read_text(encoding="utf-8")
        calculation_service = (root / "deploy/fse3d-calculation-worker@.service").read_text(
            encoding="utf-8"
        )
        deploy = (root / "scripts/deploy-release.ps1").read_text(encoding="utf-8")

        self.assertIn('revision = "0003_section_profiles"', migration)
        self.assertIn('"section_profiles"', migration)
        self.assertIn("-m pip install --disable-pip-version-check", deploy)
        self.assertIn('FSE3D_DATABASE_URL="sqlite:///$stage/.deploy-test.db"', deploy)
        self.assertIn("-m alembic current --check-heads", deploy)
        self.assertIn("-m alembic check", deploy)
        self.assertNotIn("-m alembic upgrade head", deploy)
        self.assertIn("if _auto_create_db():", deploy)
        self.assertIn("FSE3D_AUTO_CREATE_DB deve ser false", deploy)
        self.assertIn("assert_section_profiles_seeded", deploy)
        self.assertNotIn("seed_section_profiles(", deploy)
        self.assertLess(
            deploy.index("-m alembic current --check-heads"),
            deploy.index("-m alembic check"),
        )
        self.assertLess(
            deploy.index("-m alembic check"),
            deploy.index("assert_section_profiles_seeded"),
        )
        self.assertLess(
            deploy.index("assert_section_profiles_seeded"),
            deploy.index("apply_started=1"),
        )
        for removed_subsystem in (
            "database_recovery",
            "release_manifest",
            "release_provenance",
            "release_retention",
            "backup.env",
        ):
            with self.subTest(removed_subsystem=removed_subsystem):
                self.assertNotIn(removed_subsystem, deploy)
        self.assertIn('revision = "0004_calculation_jobs"', calculation_migration)
        self.assertIn('down_revision = "0003_section_profiles"', calculation_migration)
        self.assertIn('"calculation_jobs"', calculation_migration)
        self.assertIn('revision = "0006_user_admin_role"', admin_migration)
        self.assertIn('down_revision = "0005_anonymous_calculation_jobs"', admin_migration)
        self.assertIn('"is_admin"', admin_migration)
        self.assertIn('revision = "0007_admin_audit_events"', admin_audit_migration)
        self.assertIn('down_revision = "0006_user_admin_role"', admin_audit_migration)
        self.assertIn('"admin_audit_events"', admin_audit_migration)
        self.assertIn("app.calculation_worker --pool %i", calculation_service)

    def test_member_release_solver_contracts_are_wired(self) -> None:
        root = Path(__file__).resolve().parents[1]
        opensees = (root / "app/engines/opensees_engine.py").read_text(encoding="utf-8")
        factory = (root / "app/engines/factory.py").read_text(encoding="utf-8")

        self.assertIn('element_args.extend(["-releasey", release_y])', opensees)
        self.assertIn('element_args.extend(["-releasez", release_z])', opensees)
        self.assertIn("def _release_code", opensees)
        self.assertIn("OpenSeesPy elasticBeamColumn aplica releases RY/RZ", opensees)
        self.assertIn("def _solve_opensees_truss", opensees)
        self.assertIn('engine=f"{self.name}/truss"', opensees)
        self.assertIn('"pynite": "O motor PyNite', factory)
        self.assertIn('"native_truss": "O motor proprio', factory)


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