#!/usr/bin/env python3
"""
Test script to verify the cross-day fixture fix.
This script creates a yesterday fixture with 5 completed matches and 5 bet matches,
then tests that starting the game without fixture_id activates the yesterday fixture first.
"""

import sys
import os
import time
from datetime import datetime, timedelta
from pathlib import Path

# Add the project root to Python path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from mbetterclient.database.manager import DatabaseManager
from mbetterclient.database.models import MatchModel, MatchOutcomeModel
from mbetterclient.core.games_thread import GamesThread
from mbetterclient.core.message_bus import MessageBus, Message, MessageType
from mbetterclient.config.settings import get_user_data_dir

def create_yesterday_fixture_with_remaining_matches(db_manager):
    """Create a fixture from yesterday with 5 completed matches and 5 bet matches"""
    print("Creating yesterday fixture with remaining matches...")

    session = db_manager.get_session()
    try:
        # Get yesterday's date in venue timezone
        from mbetterclient.utils.timezone_utils import get_today_venue_date
        yesterday = get_today_venue_date(db_manager) - timedelta(days=1)

        # Convert to UTC for database storage
        from mbetterclient.utils.timezone_utils import venue_to_utc_datetime
        yesterday_start = datetime.combine(yesterday, datetime.min.time())
        yesterday_utc = venue_to_utc_datetime(yesterday_start, db_manager)

        # Generate fixture ID
        import uuid
        fixture_id = f"yesterday_test_{uuid.uuid4().hex[:8]}"

        # Create 5 completed matches
        for i in range(1, 6):
            match = MatchModel(
                match_number=i,
                fighter1_township=f"Fighter {i}A",
                fighter2_township=f"Fighter {i}B",
                venue_kampala_township=f"Venue {i}",
                start_time=yesterday_utc + timedelta(minutes=i*10),
                status='done',
                fixture_id=fixture_id,
                active_status=True,
                fixture_active_time=int(time.time()),
                result=f'WIN{i}A',
                end_time=yesterday_utc + timedelta(minutes=i*10 + 5),
                done=True,
                running=False,
                filename=f"match_{i}_completed.mp4",
                file_sha1sum=f"sha1_{i}_completed"
            )
            session.add(match)
            session.flush()

            # Add some outcomes
            outcome = MatchOutcomeModel(
                match_id=match.id,
                column_name=f'WIN{i}A',
                float_value=1.85
            )
            session.add(outcome)

        # Create 5 bet matches (remaining)
        for i in range(6, 11):
            match = MatchModel(
                match_number=i,
                fighter1_township=f"Fighter {i}A",
                fighter2_township=f"Fighter {i}B",
                venue_kampala_township=f"Venue {i}",
                start_time=yesterday_utc + timedelta(minutes=i*10),
                status='bet',
                fixture_id=fixture_id,
                active_status=True,
                fixture_active_time=int(time.time()),
                result=None,
                end_time=None,
                done=False,
                running=False,
                filename=f"match_{i}_bet.mp4",
                file_sha1sum=f"sha1_{i}_bet"
            )
            session.add(match)
            session.flush()

            # Add some outcomes
            outcome = MatchOutcomeModel(
                match_id=match.id,
                column_name=f'WIN{i}A',
                float_value=1.85
            )
            session.add(outcome)

        session.commit()
        print(f"Created yesterday fixture {fixture_id} with 5 completed and 5 bet matches")
        return fixture_id

    except Exception as e:
        session.rollback()
        print(f"Failed to create yesterday fixture: {e}")
        return None
    finally:
        session.close()

def test_cross_day_fixture_logic():
    """Test the cross-day fixture logic"""
    print("Testing cross-day fixture logic...")

    # Initialize database manager
    db_path = get_user_data_dir() / "mbetterclient.db"
    db_manager = DatabaseManager(str(db_path))

    if not db_manager.initialize():
        print("Failed to initialize database")
        return False

    # Create yesterday fixture
    yesterday_fixture_id = create_yesterday_fixture_with_remaining_matches(db_manager)
    if not yesterday_fixture_id:
        print("Failed to create test fixture")
        return False

    # Initialize message bus and games thread
    message_bus = MessageBus()
    games_thread = GamesThread("test_games_thread", message_bus, db_manager)

    # Mock the initialization (we don't need full initialization for this test)
    games_thread.db_manager = db_manager
    games_thread.current_fixture_id = None
    games_thread.game_active = False

    # Create a test message for START_GAME without fixture_id
    test_message = Message(
        type=MessageType.START_GAME,
        sender="test",
        recipient="games_thread",
        data={"timestamp": time.time()},
        correlation_id="test_123"
    )

    # Mock the _send_response method to capture responses
    responses = []
    original_send_response = games_thread._send_response
    def mock_send_response(message, status, response_message=None):
        responses.append({"status": status, "message": response_message})
        print(f"Mock response: {status} - {response_message}")
    games_thread._send_response = mock_send_response

    # Mock the _activate_fixture method to capture activation calls
    activations = []
    original_activate_fixture = games_thread._activate_fixture
    def mock_activate_fixture(fixture_id, message):
        activations.append(fixture_id)
        print(f"Mock activation: fixture {fixture_id}")
        # Set the current fixture to simulate activation
        games_thread.current_fixture_id = fixture_id
        games_thread.game_active = True
    games_thread._activate_fixture = mock_activate_fixture

    # Mock the _initialize_new_fixture method
    original_initialize_new_fixture = games_thread._initialize_new_fixture
    def mock_initialize_new_fixture():
        # Return a mock today fixture ID
        import uuid
        return f"today_test_{uuid.uuid4().hex[:8]}"
    games_thread._initialize_new_fixture = mock_initialize_new_fixture

    try:
        # Call the handler
        games_thread._handle_start_game(test_message)

        # Check results
        print(f"Activations: {activations}")
        print(f"Responses: {responses}")

        # Verify that yesterday fixture was activated first
        if len(activations) >= 1 and activations[0] == yesterday_fixture_id:
            print("✅ SUCCESS: Yesterday fixture was activated first")
            return True
        else:
            print(f"❌ FAILURE: Expected yesterday fixture {yesterday_fixture_id} to be activated first, got {activations}")
            return False

    except Exception as e:
        print(f"Test failed with exception: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        # Restore original methods
        games_thread._send_response = original_send_response
        games_thread._activate_fixture = original_activate_fixture
        games_thread._initialize_new_fixture = original_initialize_new_fixture

def cleanup_test_data(db_manager, fixture_id):
    """Clean up test data"""
    if not fixture_id:
        return

    print(f"Cleaning up test fixture {fixture_id}...")
    session = db_manager.get_session()
    try:
        # Delete matches and outcomes
        matches = session.query(MatchModel).filter(MatchModel.fixture_id == fixture_id).all()
        for match in matches:
            session.query(MatchOutcomeModel).filter(MatchOutcomeModel.match_id == match.id).delete()

        session.query(MatchModel).filter(MatchModel.fixture_id == fixture_id).delete()
        session.commit()
        print(f"Cleaned up test fixture {fixture_id}")
    except Exception as e:
        print(f"Failed to cleanup test data: {e}")
        session.rollback()
    finally:
        session.close()

def main():
    """Main test function"""
    print("Cross-Day Fixture Fix Test")
    print("=" * 40)

    # Initialize database manager
    db_path = get_user_data_dir() / "mbetterclient.db"
    db_manager = DatabaseManager(str(db_path))

    try:
        # Run the test
        success = test_cross_day_fixture_logic()

        if success:
            print("\n🎉 All tests passed! The cross-day fixture fix is working correctly.")
        else:
            print("\n💥 Test failed! The cross-day fixture fix needs more work.")

        return success

    except Exception as e:
        print(f"Test execution failed: {e}")
        import traceback
        traceback.print_exc()
        return False
    finally:
        db_manager.close()

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