"""
Create Test Game Script

Ends all active games and creates a new test game using real SBA lineup data.

Usage:
    uv run python scripts/create_test_game.py
"""

import asyncio
import sys
from uuid import uuid4, UUID
from pathlib import Path

# Add backend to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from app.database.session import AsyncSessionLocal
from app.database.operations import DatabaseOperations
from app.models.db_models import Game
from app.config.test_game_data import get_test_game_config
from app.services.lineup_service import lineup_service
from sqlalchemy import select, update


async def end_all_active_games(db_ops: DatabaseOperations) -> int:
    """End all active games by setting status to 'completed'."""
    async with AsyncSessionLocal() as session:
        # Find all active games
        result = await session.execute(
            select(Game).where(Game.status == 'active')
        )
        active_games = result.scalars().all()

        count = len(active_games)

        if count > 0:
            # Update all to completed
            await session.execute(
                update(Game).where(Game.status == 'active').values(status='completed')
            )
            await session.commit()
            print(f"Ended {count} active game(s)")
        else:
            print("No active games to end")

        return count


async def create_test_game(db_ops: DatabaseOperations) -> UUID:
    """Create a new test game with real SBA lineup data."""

    # Get test game configuration
    config = get_test_game_config()
    away_team = config["away_team"]
    home_team = config["home_team"]
    away_lineup = config["away_lineup"]
    home_lineup = config["home_lineup"]

    # Create game ID
    game_id = uuid4()

    print(f"\nCreating game: {game_id}")
    print(f"Away: {away_team['long_name']} ({away_team['id']})")
    print(f"Home: {home_team['long_name']} ({home_team['id']})")

    # Create game in database
    await db_ops.create_game(
        game_id=game_id,
        league_id="sba",
        home_team_id=home_team["id"],
        away_team_id=away_team["id"],
        game_mode="friendly",
        visibility="public"
    )

    # Add away team lineup (using lineup_service to fetch player data)
    print(f"\nAway lineup ({away_team['abbrev']}):")
    for player in away_lineup:
        entry = await lineup_service.add_sba_player_to_lineup(
            game_id=game_id,
            team_id=away_team["id"],
            player_id=player["player_id"],
            position=player["position"],
            batting_order=player["batting_order"],
            is_starter=True
        )
        order = player["batting_order"] if player["batting_order"] else "P"
        print(f"  {order}. {entry.player_name} ({entry.position})")

    # Add home team lineup (using lineup_service to fetch player data)
    print(f"\nHome lineup ({home_team['abbrev']}):")
    for player in home_lineup:
        entry = await lineup_service.add_sba_player_to_lineup(
            game_id=game_id,
            team_id=home_team["id"],
            player_id=player["player_id"],
            position=player["position"],
            batting_order=player["batting_order"],
            is_starter=True
        )
        order = player["batting_order"] if player["batting_order"] else "P"
        print(f"  {order}. {entry.player_name} ({entry.position})")

    # Update game status to active
    async with AsyncSessionLocal() as session:
        await session.execute(
            update(Game).where(Game.id == game_id).values(
                status="active",
                current_inning=1,
                current_half="top"
            )
        )
        await session.commit()

    print(f"\nGame created and activated: {game_id}")
    return game_id


async def main():
    """Main function to end active games and create a new test game."""
    print("=" * 60)
    print("Test Game Creator")
    print("=" * 60)

    db_ops = DatabaseOperations()

    # End all active games
    await end_all_active_games(db_ops)

    # Create new test game
    game_id = await create_test_game(db_ops)

    print("\n" + "=" * 60)
    print(f"SUCCESS! Test game ready: {game_id}")
    print("=" * 60)

    return game_id


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