#!/usr/bin/env python3
"""
Script to create a bet with one bet detail for every possible outcome on the next match
"""

import sys
from pathlib import Path
from datetime import datetime, timezone
import uuid as uuid_lib

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

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

def create_bet_for_all_outcomes():
    """Create a bet with one bet detail for every possible outcome on the next match"""

    # 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:
        # Find the next match - look for matches with status 'bet' (available for betting)
        # Order by start_time ascending to get the next one
        next_match = session.query(MatchModel).filter(
            MatchModel.status == 'bet'
        ).order_by(MatchModel.start_time.asc()).first()

        if not next_match:
            print("No upcoming matches found with status 'bet' or 'scheduled'")
            return False

        print(f"Found next match: #{next_match.match_number} - {next_match.fighter1_township} vs {next_match.fighter2_township}")
        print(f"Match status: {next_match.status}, Start time: {next_match.start_time}")

        # Get all possible outcomes for this match
        outcomes = session.query(MatchOutcomeModel).filter_by(match_id=next_match.id).all()

        if not outcomes:
            print(f"No outcomes found for match {next_match.id}")
            return False

        print(f"Found {len(outcomes)} possible outcomes:")
        for outcome in outcomes:
            print(f"  - {outcome.column_name}: {outcome.float_value}")

        # Create separate bets for each outcome
        bet_datetime = datetime.now(timezone.utc)
        created_bets = []

        for outcome in outcomes:
            # Generate UUID for each bet
            bet_uuid = str(uuid_lib.uuid4())

            # Create the bet record (disable barcode for test bets to avoid conflicts)
            new_bet = BetModel(
                uuid=bet_uuid,
                bet_datetime=bet_datetime,
                fixture_id=next_match.fixture_id,
                barcode_standard='none',
                barcode_data=None
            )
            session.add(new_bet)

            # Create bet detail for this outcome
            bet_detail = BetDetailModel(
                bet_id=bet_uuid,
                match_id=next_match.id,
                outcome=outcome.column_name,
                amount=1.0,  # Fixed amount of 1.0 for each bet
                result='pending'
            )
            session.add(bet_detail)

            created_bets.append({
                'uuid': bet_uuid,
                'outcome': outcome.column_name,
                'amount': 1.0
            })

        # Commit the transaction
        try:
            session.commit()
            print(f"\n✅ Successfully created {len(created_bets)} separate bets")
            print(f"   - Match: #{next_match.match_number} ({next_match.fighter1_township} vs {next_match.fighter2_township})")
            print(f"   - Bet datetime: {bet_datetime}")
            print("   - Bets created:")
            for bet in created_bets:
                print(f"     * {bet['uuid'][:8]}... - {bet['outcome']} - ${bet['amount']}")

            return True

        except Exception as commit_error:
            print(f"Commit failed: {commit_error}")
            session.rollback()
            return False

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

if __name__ == "__main__":
    print("Creating bet for all possible outcomes on the next match...")
    success = create_bet_for_all_outcomes()
    if success:
        print("\n🎯 Bet created successfully!")
        print("You can now view the bet in the web dashboard.")
    else:
        print("\n❌ Failed to create bet.")
        sys.exit(1)