#!/usr/bin/env python3
"""
Test script for the GamesThread component
"""

import sys
import os
import time
import logging

# Add the project root to Python path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from mbetterclient.core.games_thread import GamesThread
from mbetterclient.core.message_bus import MessageBus, Message, MessageType
from mbetterclient.database.manager import DatabaseManager

# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def test_games_thread():
    """Test the GamesThread component"""
    try:
        logger.info("Testing GamesThread component...")

        # Create a message bus
        message_bus = MessageBus()

        # Create a mock database manager (we won't actually connect to DB)
        class MockDBManager:
            def get_session(self):
                class MockSession:
                    def query(self, model):
                        return self
                    def filter(self, *args):
                        return self
                    def order_by(self, *args):
                        return self
                    def first(self):
                        return None  # No matches for this test
                    def close(self):
                        pass
                return MockSession()

        db_manager = MockDBManager()

        # Create games thread
        games_thread = GamesThread(
            name="test_games_thread",
            message_bus=message_bus,
            db_manager=db_manager
        )

        # Test initialization
        logger.info("Testing initialization...")
        if not games_thread.initialize():
            logger.error("Failed to initialize GamesThread")
            return False

        logger.info("GamesThread initialized successfully")

        # Test START_GAME message handling
        logger.info("Testing START_GAME message handling...")
        start_game_message = Message(
            type=MessageType.START_GAME,
            sender="test",
            data={
                "fixture_id": "test_fixture_123"
            }
        )

        # Send the message
        message_bus.publish(start_game_message)

        # Give it a moment to process
        time.sleep(0.5)

        # Test START_GAMES message handling
        logger.info("Testing START_GAMES message handling...")
        start_games_message = Message(
            type=MessageType.SCHEDULE_GAMES,
            sender="test",
            data={
                "fixture_id": "test_fixture_456"
            }
        )

        # Send the message
        message_bus.publish(start_games_message)

        # Give it a moment to process
        time.sleep(0.5)

        # Test shutdown
        logger.info("Testing shutdown...")
        games_thread.shutdown()

        logger.info("GamesThread test completed successfully")
        return True

    except Exception as e:
        logger.error(f"GamesThread test failed: {e}")
        import traceback
        traceback.print_exc()
        return False

if __name__ == "__main__":
    success = test_games_thread()
    sys.exit(0 if success else 1)