#!/usr/bin/env python3
"""
Test script to verify the bet cancellation logic directly
"""

from mbetterclient.database.models import BetModel, BetDetailModel, MatchModel
from mbetterclient.database.manager import DatabaseManager
from mbetterclient.config.settings import get_user_data_dir

def test_cancel_logic():
    """Test the cancel logic directly"""

    # Use the default database path
    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

    session = db_manager.get_session()
    try:
        # Get all bets and check their matches
        bets = session.query(BetModel).all()
        print(f"Found {len(bets)} bets total")

        for bet in bets:
            print(f"\nTesting cancellation for bet: {bet.uuid}")

            # Get bet details
            bet_details = session.query(BetDetailModel).filter_by(bet_id=bet.uuid).all()
            print(f"Bet has {len(bet_details)} details")

            # Check if any match has already started
            match_ids = [detail.match_id for detail in bet_details]
            matches = session.query(MatchModel).filter(MatchModel.id.in_(match_ids)).all()

            print("Match statuses:")
            for match in matches:
                print(f"  Match {match.id}: {match.status}")

            # Check the logic
            blocked = any(match.status in ['ingame', 'done'] for match in matches)
            if blocked:
                print("❌ Cancellation should be BLOCKED - match has already started")
            else:
                print("✅ Cancellation should be ALLOWED - no matches have started yet")
                return True  # Found one that should be allowed

        print("\nAll existing bets are on matches that have already started.")
        return True

        # Get bet details
        bet_details = session.query(BetDetailModel).filter_by(bet_id=bet.uuid).all()
        print(f"Bet has {len(bet_details)} details")

        # Check if any match has already started
        match_ids = [detail.match_id for detail in bet_details]
        matches = session.query(MatchModel).filter(MatchModel.id.in_(match_ids)).all()

        print("Match statuses:")
        for match in matches:
            print(f"  Match {match.id}: {match.status}")

        # Check the logic
        if any(match.status in ['ingame', 'done'] for match in matches):
            print("❌ Cancellation should be BLOCKED - match has already started")
            return True  # Test passed - correctly blocked
        else:
            print("✅ Cancellation should be ALLOWED - no matches have started yet")
            return True  # Test passed - correctly allowed

    except Exception as e:
        print(f"Error: {e}")
        return False
    finally:
        session.close()
        db_manager.close()

if __name__ == "__main__":
    print("Testing bet cancellation logic...")
    success = test_cancel_logic()
    if success:
        print("\n✅ Logic test completed successfully!")
    else:
        print("\n❌ Logic test failed.")