from dataclasses import dataclass from datetime import datetime, timezone from typing import Any, Mapping import numpy as np from app.services.raw_schema import ( BOOLEAN_RAW_COLUMNS, FIELD_ALIASES, NUMERIC_RAW_COLUMNS, NORMALIZED_RAW_COLUMNS, STRING_RAW_COLUMNS, ) _MISSING = object() @dataclass(frozen=True, slots=True) class NormalizedEvent: topic: str fields: dict[str, Any] received_at: datetime source_fields: tuple[str, ...] class RawNormalizer: """Map one flattened provider record to canonical FastF1-style fields.""" def normalize(self, topic: str, record: Mapping[str, Any]) -> NormalizedEvent: flattened = self._flatten(record) casefold_lookup = {key.casefold(): key for key in flattened} normalized: dict[str, Any] = {} for canonical in NORMALIZED_RAW_COLUMNS: if canonical in {"TotalLaps", "CurrentLap"} and topic != "LapCount": continue aliases = FIELD_ALIASES.get(canonical, (canonical,)) if topic in {"TyreStintSeries", "CurrentTyres"}: aliases += { "TyreLife": ("TotalLaps",), "FreshTyre": ("New",), }.get(canonical, ()) if topic in {"TimingData", "TimingStats", "TimingDataF1"}: aliases += { "SpeedI1": ("Speeds_I1_Value",), "SpeedI2": ("Speeds_I2_Value",), "SpeedFL": ("Speeds_FL_Value",), "SpeedST": ("Speeds_ST_Value",), "LapTime": ("LastLapTime_Value",), "IsPersonalBest": ("LastLapTime_PersonalFastest",), }.get(canonical, ()) if topic == "SessionStatus" and canonical == "SessionStatus": aliases = aliases + ("Status",) elif topic == "TrackStatus" and canonical == "TrackStatus": aliases = aliases + ("Status",) value = self._first_present(flattened, casefold_lookup, aliases) if value is not _MISSING: normalized[canonical] = self._coerce(canonical, value) if topic == "TyreStintSeries" and "PitCount" in flattened: pit_count = self._coerce("Stint", flattened["PitCount"]) if pit_count is not None: normalized["Stint"] = pit_count + 1 return NormalizedEvent( topic=topic, fields=normalized, received_at=datetime.now(timezone.utc), source_fields=tuple(sorted(flattened)), ) @staticmethod def _flatten(record: Mapping[str, Any]) -> dict[str, Any]: result: dict[str, Any] = {} def visit(value: Any, prefix: str = "") -> None: if not isinstance(value, Mapping): if prefix: result[prefix] = value result.setdefault(prefix.rsplit(".", 1)[-1], value) return for key, child in value.items(): visit(child, f"{prefix}.{key}" if prefix else str(key)) visit(record) return result @staticmethod def _first_present( flattened: Mapping[str, Any], casefold_lookup: Mapping[str, str], aliases: tuple[str, ...], ) -> Any: for alias in aliases: if alias in flattened: return flattened[alias] actual = casefold_lookup.get(alias.casefold()) if actual is not None: return flattened[actual] return _MISSING @staticmethod def _coerce(column: str, value: Any) -> Any: if value is None: return None if column in BOOLEAN_RAW_COLUMNS: if isinstance(value, bool): return int(value) text = str(value).strip().casefold() if text in {"true", "yes", "1"}: return 1 if text in {"false", "no", "0"}: return 0 if column in NUMERIC_RAW_COLUMNS: try: if column in {"LapTime", "Sector1Time", "Sector2Time", "Sector3Time"} and isinstance(value, str) and ":" in value: number = 0.0 for part in value.split(":"): number = number * 60 + float(part) else: number = float(value) except (TypeError, ValueError): return None return number if np.isfinite(number) else None if column in STRING_RAW_COLUMNS: text = str(value).strip() if not text: return None return text.upper() if column in {"Driver", "Compound"} else text return value