"""
Tests for AiogramAdapter.

Tests verify that:
- Adapter is properly created via UIRouterExecutor
- Router is properly created with handlers registered
- Basic handler registration works correctly
- Integration with UIRouterExecutor services is correct
"""

import pytest
from aiogram import Router

from ui_router import (
    UIRouter,
    UIRouterExecutor,
    Scene,
    Handler,
    EventType,
    MessageContent,
)
from ui_router.schema import SendMessageAction


@pytest.fixture
def minimal_schema():
    """Create a minimal UIRouter schema for testing."""
    return UIRouter(
        name="test_router",
        initial_scene="welcome",
        scenes=[
            Scene(
                id="welcome",
                name="Welcome Scene",
                default_content=MessageContent(text="Welcome"),
                handlers=[
                    Handler(
                        name="start_handler",
                        event_type=EventType.MESSAGE,
                        filters=[],
                        conditions=[],
                        actions=[
                            SendMessageAction(
                                content=MessageContent(text="Hello"),
                            )
                        ],
                    )
                ],
            )
        ],
    )


@pytest.fixture
def executor(minimal_schema, shared_services):
    """Create a UIRouterExecutor for testing."""
    return UIRouterExecutor(
        schema=minimal_schema,
        shared=shared_services,
    )


class TestAiogramAdapterCreation:
    """Test AiogramAdapter creation and initialization."""

    def test_adapter_created_by_executor(self, executor):
        """Test that adapter is created by UIRouterExecutor."""
        adapter = executor.aiogram_adapter
        assert adapter is not None

    def test_router_is_created(self, executor):
        """Test that aiogram Router is created."""
        adapter = executor.aiogram_adapter
        assert adapter.router is not None
        assert isinstance(adapter.router, Router)

    def test_router_name_matches_schema(self, executor):
        """Test that router name matches schema name."""
        adapter = executor.aiogram_adapter
        assert adapter.router.name == executor.schema.name

    def test_get_router_method(self, executor):
        """Test that get_router returns the registered router."""
        adapter = executor.aiogram_adapter
        router = adapter.get_router()
        assert router is adapter.router

    def test_executor_get_router(self, executor):
        """Test that executor.get_router() returns the adapter's router."""
        router = executor.get_router()
        assert router is executor.aiogram_adapter.router


class TestAiogramAdapterIntegration:
    """Test AiogramAdapter integration with UIRouterExecutor."""

    def test_adapter_can_access_schema(self, executor):
        """Test that adapter has access to schema."""
        adapter = executor.aiogram_adapter
        assert adapter.schema is not None

    def test_adapter_with_global_handlers(self, shared_services):
        """Test adapter registration with global handlers."""
        from ui_router import GlobalHandler

        schema = UIRouter(
            name="test_global",
            initial_scene="welcome",
            global_handlers=[
                GlobalHandler(
                    name="help_handler",
                    event_type=EventType.MESSAGE,
                    filters=[],
                    conditions=[],
                    actions=[
                        SendMessageAction(
                            content=MessageContent(text="Help"),
                        )
                    ],
                    priority=10,
                )
            ],
            scenes=[
                Scene(
                    id="welcome",
                    name="Welcome Scene",
                    default_content=MessageContent(text="Welcome"),
                    handlers=[],
                )
            ],
        )

        executor = UIRouterExecutor(schema=schema, shared=shared_services)
        assert executor.aiogram_adapter.router is not None

    def test_adapter_with_multiple_scenes(self, shared_services):
        """Test adapter with multiple scenes and handlers."""
        schema = UIRouter(
            name="test_multi_scene",
            initial_scene="scene1",
            scenes=[
                Scene(
                    id="scene1",
                    name="Scene 1",
                    default_content=MessageContent(text="Scene 1"),
                    handlers=[
                        Handler(
                            name="handler1",
                            event_type=EventType.MESSAGE,
                            filters=[],
                            conditions=[],
                            actions=[],
                        )
                    ],
                ),
                Scene(
                    id="scene2",
                    name="Scene 2",
                    default_content=MessageContent(text="Scene 2"),
                    handlers=[
                        Handler(
                            name="handler2",
                            event_type=EventType.MESSAGE,
                            filters=[],
                            conditions=[],
                            actions=[],
                        )
                    ],
                ),
            ],
        )

        executor = UIRouterExecutor(schema=schema, shared=shared_services)
        assert executor.aiogram_adapter.router is not None


class TestAiogramAdapterFilters:
    """Test filter building in AiogramAdapter."""

    def test_build_filters_from_schema(self, executor):
        """Test that filters are built from schema."""
        from ui_router import Filter

        adapter = executor.aiogram_adapter

        # Test text filter
        text_filter = Filter(type="text", text="hello")
        filters = adapter._build_filters([text_filter])
        assert len(filters) > 0

        # Test command filter
        command_filter = Filter(type="command", commands=["start"])
        filters = adapter._build_filters([command_filter])
        assert len(filters) > 0

    def test_create_navigation_filter(self, executor):
        """Test navigation filter creation."""
        adapter = executor.aiogram_adapter

        # With require_state=True
        nav_filter = adapter._create_navigation_filter(require_state=True)
        assert nav_filter is not None
        assert callable(nav_filter)

        # With require_state=False
        nav_filter = adapter._create_navigation_filter(require_state=False)
        assert nav_filter is None

    def test_build_condition_filters_empty(self, executor):
        """Test condition filters with empty conditions list."""
        adapter = executor.aiogram_adapter
        filters = adapter._build_condition_filters([])
        assert len(filters) == 0

    def test_build_condition_filters_with_conditions(self, executor):
        """Test condition filters with conditions."""
        adapter = executor.aiogram_adapter
        filters = adapter._build_condition_filters(["some_condition"])
        assert len(filters) > 0


class TestAiogramAdapterConsistency:
    """Test that AiogramAdapter produces consistent results."""

    def test_adapter_router_has_schema_name(self, minimal_schema, shared_services):
        """Test that router name matches schema name."""
        executor = UIRouterExecutor(
            schema=minimal_schema,
            shared=shared_services,
        )
        adapter = executor.aiogram_adapter

        assert adapter.router.name == minimal_schema.name
        assert adapter.router.name == "test_router"
