from typing import Optional, TYPE_CHECKING from fastf1.ergast import Ergast import slugify # Import FastF1 for dynamic circuit data import fastf1 import logging if TYPE_CHECKING: from circuits_service import CircuitService class ErgastService: country_map = { "united-kingdom": "uk", } def __init__(self, circuits_service: 'CircuitService' = None): self.circuits_service = circuits_service # Configure logging logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger(__name__) # Initialize FastF1 cache fastf1.Cache.enable_cache('cache') def find_slugs_for_grand_prix(self, grand_prix_name: str, season: int) -> Optional[tuple[str, str, str]]: """ Find and return the circuit layout file path based on Ergast F1 API race data format. """ try: ergast = Ergast() f1_event = fastf1.events.get_event(int(season), grand_prix_name) f1_seasons = ergast.get_race_schedule(season=season) f1_season = f1_seasons[f1_seasons["raceName"] == grand_prix_name] country_slug = slugify.slugify(f1_event["Country"]) city_slug = slugify.slugify(f1_season["locality"].values[0]) circuit_slug = slugify.slugify(f1_season["circuitName"].values[0]) return self.country_map[country_slug] if country_slug in self.country_map else country_slug, city_slug, circuit_slug except Exception as e: self.logger.error( f"Error finding circuit layout in Ergast for grand prix {grand_prix_name} in season {season}: {str(e)}") return None