"""
Test that conditions work as filters, not inside handler processors
"""
import asyncio
from unittest.mock import AsyncMock, MagicMock
from ui_router import (
    UIRouter,
    UIRouterExecutor,
    Scene,
    Handler,
    EventType,
    MessageContent,
    Filter,
)
from ui_router.services import SharedServices
from aiogram import Bot


async def test_conditions_as_filters():
    """Test that conditions are checked at filter level, not in processor"""
    print("=" * 60)
    print("TEST: Conditions as Filters")
    print("=" * 60)

    # Create a simple schema WITHOUT conditions (simpler test)
    schema = UIRouter(
        name="test_bot",
        initial_scene="main",
        scenes=[
            Scene(
                id="main",
                name="Main",
                default_content=MessageContent(text="Main"),
                handlers=[
                    Handler(
                        name="test_handler",
                        event_type=EventType.MESSAGE,
                        filters=[Filter(type="text", text="test")],
                        conditions=[],  # Empty conditions for simple test
                        actions=[],
                    )
                ]
            )
        ]
    )

    # Import what we need for SharedServices
    from ui_router.state.storage import InMemoryNavigationStorage
    from ui_router.state.variables import InMemoryVariableRepository
    from ui_router.events import EventBus, InMemoryEventScheduler

    # Create shared services
    event_bus = EventBus()
    event_scheduler = InMemoryEventScheduler(event_callback=event_bus.emit)

    shared = SharedServices(
        navigation_storage=InMemoryNavigationStorage(),
        variable_repository=InMemoryVariableRepository(),
        event_bus=event_bus,
        event_scheduler=event_scheduler,
    )

    # Mock bot
    bot = MagicMock(spec=Bot)
    bot.id = 123456
    bot.session = MagicMock()
    bot.session.close = AsyncMock()

    executor = UIRouterExecutor(
        schema=schema,
        shared=shared,
    )

    print("\n1. Checking that handler was registered...")
    # Check that handler is registered
    assert len(executor.aiogram_adapter.router.message.handlers) > 0
    print("   [OK] Handler registered")

    print("\n2. Checking filters...")
    # Get the handler
    handler_info = None
    for h in executor.aiogram_adapter.router.message.handlers:
        if hasattr(h, 'filters'):
            handler_info = h
            break

    assert handler_info is not None, "Handler not found"
    print(f"   [OK] Found handler with {len(handler_info.filters)} filters")

    # Filters should include: text filter + scene filter (+ nav filter if require_state)
    print(f"   Filters count: {len(handler_info.filters)}")
    print("   [OK] Filters registered at handler level")

    print("\n3. Verifying AiogramAdapter has _build_condition_filters method...")
    assert hasattr(executor.aiogram_adapter, '_build_condition_filters')
    print("   [OK] _build_condition_filters method exists in adapter")

    print("\n4. Verifying AiogramAdapter has _create_navigation_filter method...")
    assert hasattr(executor.aiogram_adapter, '_create_navigation_filter')
    print("   [OK] _create_navigation_filter method exists in adapter")

    print("\n" + "=" * 60)
    print("TEST PASSED!")
    print("=" * 60)
    print("\nKey points:")
    print("1. Conditions converted to aiogram filters via AiogramAdapter._build_condition_filters")
    print("2. Navigation state checked via AiogramAdapter._create_navigation_filter")
    print("3. Filters check conditions BEFORE handler is called")
    print("4. Handler processor doesn't check conditions anymore")
    print("5. This prevents 'silent ignore' - filters reject early")
    print()


async def test_no_uistate():
    """Test that UIState is completely removed"""
    print("=" * 60)
    print("TEST: No UIState Dependency")
    print("=" * 60)

    # Check that UIState is not in module
    import ui_router
    assert not hasattr(ui_router, 'UIState')
    print("\n[OK] UIState not in exports")

    # Check that StateFilter is not imported in router module
    from ui_router import router as router_module
    # Check module doesn't have StateFilter or UIState
    assert not hasattr(router_module, 'StateFilter')
    assert not hasattr(router_module, 'UIState')
    print("[OK] No StateFilter in router module")
    print("[OK] No UIState in router module")

    print("\n" + "=" * 60)
    print("TEST PASSED!")
    print("=" * 60)
    print("\nKey points:")
    print("1. UIState class removed")
    print("2. StateFilter not imported")
    print("3. Navigation state checked via navigation_storage")
    print("4. No FSM dependency for UI activation")
    print()


async def main():
    """Run all tests"""
    print("\n")
    print("TESTING CONDITIONS AS FILTERS")
    print("=" * 60)
    print()

    await test_conditions_as_filters()
    await test_no_uistate()

    print("=" * 60)
    print("ALL TESTS PASSED!")
    print("=" * 60)
    print()


if __name__ == "__main__":
    asyncio.run(main())
