"""Tests for web app creation."""

from pathlib import Path

import pytest

from impakt.io.mme import MMEReader
from impakt.web.app import create_app
from impakt.web.state import AppState

FIXTURE_DATA = Path(__file__).parent.parent / "fixtures" / "sample_mme"
MME_DATA = Path(__file__).parent.parent / "mme_data"


class TestAppCreation:
    def test_create_empty_app(self):
        app = create_app()
        assert app is not None
        assert app.title == "Impakt"

    def test_create_app_with_test_data(self):
        reader = MMEReader()
        data = reader.read(FIXTURE_DATA)
        app = create_app(data)
        assert app is not None
        assert "IMPAKT_SYNTH_001" in app.title

    def test_create_app_with_app_state(self):
        state = AppState()
        state.load_test(FIXTURE_DATA)
        app = create_app(app_state=state)
        assert app is not None
        assert "IMPAKT_SYNTH_001" in app.title

    @pytest.mark.skipif(not (MME_DATA / "3239").exists(), reason="Real data not available")
    def test_create_app_with_real_data(self):
        state = AppState()
        state.load_test(MME_DATA / "3239")
        app = create_app(app_state=state)
        assert app is not None
        assert "3239" in app.title


class TestCriteriaAutoCompute:
    def test_auto_compute_on_synthetic_data(self):
        from impakt.web.components.criteria import auto_compute_criteria

        reader = MMEReader()
        data = reader.read(FIXTURE_DATA)

        criteria = auto_compute_criteria(data)
        # Synthetic data should have head accel -> HIC15
        assert len(criteria) > 0
        # Should at least get HIC15 and chest deflection
        criterion_names = set(criteria.keys())
        assert "HIC15" in criterion_names or "Chest Deflection" in criterion_names

    @pytest.mark.skipif(not (MME_DATA / "3239").exists(), reason="Real data not available")
    def test_auto_compute_on_real_data(self):
        from impakt.web.components.criteria import auto_compute_criteria

        reader = MMEReader()
        data = reader.read(MME_DATA / "3239")

        criteria = auto_compute_criteria(data)
        # Real NHTSA data should yield multiple criteria
        assert len(criteria) >= 3
        criterion_names = set(criteria.keys())
        # 3239 has head, chest, neck, femur channels
        assert "HIC15" in criterion_names

    @pytest.mark.skipif(not (MME_DATA / "3239").exists(), reason="Real data not available")
    def test_protocol_scoring_on_real_data(self):
        from impakt.web.components.criteria import auto_compute_criteria, score_protocol

        reader = MMEReader()
        data = reader.read(MME_DATA / "3239")

        criteria = auto_compute_criteria(data)
        for protocol in ["euro_ncap", "us_ncap", "iihs"]:
            result = score_protocol(criteria, protocol)
            assert result is not None
            assert len(result.region_scores) > 0
