from __future__ import annotations

import unittest

from sqlalchemy import create_engine, select
from sqlalchemy.orm import Session

from app.database import Base
from app.models import SectionProfile
from app.section_profile_seed import (
    GERDAU_W_SERIES_I_PROFILES,
    GERDAU_W_SERIES_I_SOURCE,
    assert_section_profiles_seeded,
    seed_section_profiles,
)

SECTION_MODULUS_ROUNDING_TOLERANCE = 0.01


class SectionProfileSeedContractTests(unittest.TestCase):
    def setUp(self) -> None:
        self.engine = create_engine("sqlite:///:memory:")
        Base.metadata.create_all(self.engine)
        with Session(self.engine) as database:
            seed_section_profiles(database)

    def tearDown(self) -> None:
        self.engine.dispose()

    def test_exact_catalog_passes_without_database_mutation(self) -> None:
        with Session(self.engine) as database:
            before = tuple(
                database.execute(
                    select(SectionProfile.profile_key, SectionProfile.label).order_by(
                        SectionProfile.profile_key
                    )
                ).all()
            )
            assert_section_profiles_seeded(database)
            after = tuple(
                database.execute(
                    select(SectionProfile.profile_key, SectionProfile.label).order_by(
                        SectionProfile.profile_key
                    )
                ).all()
            )
            self.assertEqual(after, before)
            self.assertFalse(database.new)
            self.assertFalse(database.dirty)
            self.assertFalse(database.deleted)

    def test_mysql_float_round_trip_passes_without_database_mutation(self) -> None:
        expected_rows = {
            row["profile_key"]: {**GERDAU_W_SERIES_I_SOURCE, **row}
            for row in GERDAU_W_SERIES_I_PROFILES
        }
        with Session(self.engine) as database:
            managed = database.execute(
                select(SectionProfile).where(
                    SectionProfile.source_id
                    == GERDAU_W_SERIES_I_SOURCE["source_id"]
                )
            ).scalars().all()
            for profile in managed:
                for field, expected in expected_rows[profile.profile_key].items():
                    if isinstance(expected, float):
                        setattr(profile, field, float(f"{expected:.6g}"))
            database.commit()

        with Session(self.engine) as database:
            assert_section_profiles_seeded(database)
            self.assertFalse(database.new)
            self.assertFalse(database.dirty)
            self.assertFalse(database.deleted)

    def test_material_float_divergence_fails_conservatively(self) -> None:
        with Session(self.engine) as database:
            profile = database.execute(
                select(SectionProfile).where(
                    SectionProfile.profile_key == "GERDAU_W150X13.0"
                )
            ).scalar_one()
            profile.area_m2 *= 1.0001
            database.commit()

        with Session(self.engine) as database:
            with self.assertRaisesRegex(
                RuntimeError,
                "divergentes=GERDAU_W150X13.0",
            ):
                assert_section_profiles_seeded(database)

    def test_missing_managed_profile_fails_conservatively(self) -> None:
        with Session(self.engine) as database:
            managed = database.execute(
                select(SectionProfile)
                .where(
                    SectionProfile.source_id
                    == GERDAU_W_SERIES_I_SOURCE["source_id"]
                )
                .order_by(SectionProfile.profile_key)
            ).scalars().all()
            database.delete(managed[0])
            database.commit()

        with Session(self.engine) as database:
            with self.assertRaisesRegex(
                RuntimeError,
                "Catalogo de perfis exige operacao explicita",
            ):
                assert_section_profiles_seeded(database)

    def test_changed_non_float_field_fails_conservatively(self) -> None:
        with Session(self.engine) as database:
            profile = database.execute(
                select(SectionProfile).where(
                    SectionProfile.profile_key == "GERDAU_W150X13.0"
                )
            ).scalar_one()
            profile.label = "catalogo adulterado"
            database.commit()

        with Session(self.engine) as database:
            with self.assertRaisesRegex(
                RuntimeError,
                "divergentes=GERDAU_W150X13.0",
            ):
                assert_section_profiles_seeded(database)

    def test_unexpected_managed_profile_fails_conservatively(self) -> None:
        with Session(self.engine) as database:
            profile = database.execute(
                select(SectionProfile).where(
                    SectionProfile.profile_key == "GERDAU_W150X13.0"
                )
            ).scalar_one()
            profile.profile_key = "GERDAU_UNEXPECTED"
            database.commit()

        with Session(self.engine) as database:
            with self.assertRaisesRegex(
                RuntimeError,
                "inesperados=GERDAU_UNEXPECTED",
            ):
                assert_section_profiles_seeded(database)

    def test_all_68_profiles_fit_declared_section_modulus_rounding_tolerance(
        self,
    ) -> None:
        self.assertEqual(len(GERDAU_W_SERIES_I_PROFILES), 68)
        discrepancies: list[tuple[float, str, str]] = []
        for profile in GERDAU_W_SERIES_I_PROFILES:
            expected_strong = 2.0 * profile["ix_m4"] / profile["d_m"]
            expected_weak = 2.0 * profile["iy_m4"] / profile["bf_m"]
            discrepancies.extend(
                (
                    (
                        abs(profile["wx_m3"] - expected_strong) / expected_strong,
                        profile["profile_key"],
                        "forte",
                    ),
                    (
                        abs(profile["wy_m3"] - expected_weak) / expected_weak,
                        profile["profile_key"],
                        "fraco",
                    ),
                )
            )

        maximum, profile_key, axis = max(discrepancies)
        self.assertLessEqual(maximum, SECTION_MODULUS_ROUNDING_TOLERANCE)
        self.assertLess(
            maximum,
            0.005,
            f"o envelope observado do catalogo mudou em {profile_key}, eixo {axis}",
        )

    def test_all_68_profiles_fit_independent_physical_geometry_bounds(self) -> None:
        tolerance = 0.01
        self.assertEqual(len(GERDAU_W_SERIES_I_PROFILES), 68)
        for profile in GERDAU_W_SERIES_I_PROFILES:
            with self.subTest(profile=profile["profile_key"]):
                area = profile["area_m2"]
                depth = profile["d_m"]
                width = profile["bf_m"]
                web = profile["tw_m"]
                flange = profile["tf_m"]
                clear_height = profile["h_m"]
                iy = profile["ix_m4"]
                iz = profile["iy_m4"]
                minimum_rectangular_area = (
                    2.0 * width * flange + clear_height * web
                )

                self.assertLessEqual(area, depth * width * (1.0 + tolerance))
                self.assertGreaterEqual(
                    area,
                    minimum_rectangular_area * (1.0 - tolerance),
                )
                self.assertLessEqual(
                    iy,
                    area * (depth / 2.0) ** 2 * (1.0 + tolerance),
                )
                self.assertLessEqual(
                    iz,
                    area * (width / 2.0) ** 2 * (1.0 + tolerance),
                )
                self.assertLessEqual(
                    profile["zx_m3"],
                    area * depth / 2.0 * (1.0 + tolerance),
                )
                self.assertLessEqual(
                    profile["zy_m3"],
                    area * width / 2.0 * (1.0 + tolerance),
                )


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