diff --git a/in_game/ai_manager.py b/in_game/ai_manager.py index 5dcff49..7e5ff72 100644 --- a/in_game/ai_manager.py +++ b/in_game/ai_manager.py @@ -13,7 +13,8 @@ from typing import Optional, Literal from in_game import data_cache from in_game.gameplay_models import Play, Session, Game, Team, Lineup -from in_game.gameplay_queries import get_or_create_ai_card, get_player_id_from_dict, get_player_or_none +from in_game.gameplay_queries import get_or_create_ai_card, get_player_id_from_dict, get_player_or_none, get_pitcher_scouting_or_none +from exceptions import DatabaseError db = SqliteDatabase( 'storage/ai-database.db', @@ -342,11 +343,48 @@ async def get_starting_pitcher( sp_rank = 5 logger.info(f'chosen rank: {sp_rank}') - sp_query = await db_get( - f'teams/{this_team.id}/sp/{league_name}?sp_rank={sp_rank}{this_game.cardset_param_string}' - ) - this_player = await get_player_or_none(session, get_player_id_from_dict(sp_query)) - sp_card = await get_or_create_ai_card(session, this_player, this_team) + # Try to get a pitcher with valid pitching data, retrying with different ranks if needed + original_rank = sp_rank + tried_ranks = set() + direction = 1 # 1 = incrementing, -1 = decrementing + + while len(tried_ranks) < 5: + tried_ranks.add(sp_rank) + logger.info(f'Trying sp_rank: {sp_rank}') + + sp_query = await db_get( + f'teams/{this_team.id}/sp/{league_name}?sp_rank={sp_rank}{this_game.cardset_param_string}' + ) + this_player = await get_player_or_none(session, get_player_id_from_dict(sp_query)) + sp_card = await get_or_create_ai_card(session, this_player, this_team) + + # Validate pitcher has pitching data + try: + pitcher_scouting = await get_pitcher_scouting_or_none(session, sp_card) + if pitcher_scouting is not None: + sp_card.pitcherscouting = pitcher_scouting + session.add(sp_card) + session.commit() + session.refresh(sp_card) + logger.info(f'Found valid pitcher at rank {sp_rank}: {this_player.name_with_desc}') + break + else: + logger.warning(f'Pitcher at rank {sp_rank} ({this_player.name_with_desc}) returned None for pitcherscouting') + except DatabaseError: + logger.warning(f'Pitcher at rank {sp_rank} ({this_player.name_with_desc}) lacks pitching data, trying another') + + # Adjust rank: increment first, if we hit 6, switch to decrementing from original + sp_rank += direction + if sp_rank > 5: + direction = -1 + sp_rank = original_rank - 1 + if sp_rank < 1: + # Find any untried rank + untried = [r for r in range(1, 6) if r not in tried_ranks] + if untried: + sp_rank = untried[0] + else: + break return Lineup( team=this_team,