"""Odds comparison client for comparing model probabilities vs market odds.

Fetches market odds from supported bookmakers and compares them
against the TipSharks rating engine's win/place probabilities to
identify discrepancies.
"""

from __future__ import annotations

from decimal import Decimal
from typing import Any


class OddsComparisonClient:
    """Compares model probabilities against market odds.

    Supports multiple bookmaker APIs and provides normalized odds
    in both decimal and implied probability formats.
    """

    def __init__(
        self,
        bookmaker: str = "tab_nz",
        api_key: str | None = None,
    ) -> None:
        """Initialize the odds comparison client.

        Args:
            bookmaker: Target bookmaker identifier (e.g., "tab_nz",
                "bet365", "sportsbet").
            api_key: Optional API key for bookmaker odds feed.
        """
        self.bookmaker = bookmaker
        self.api_key = api_key
        self._odds_cache: dict[str, Any] = {}

    async def get_race_odds(
        self,
        race_id: int,
    ) -> list[dict[str, Any]]:
        """Fetch current market odds for all runners in a race.

        Args:
            race_id: The race ID.

        Returns:
            List of odds dicts with keys:
            - runner_name: str
            - win_odds_decimal: Decimal
            - win_probability: float (1 / odds, adjusted for margin)
            - place_odds: Decimal | None
            - last_updated: str (ISO datetime)
        """
        raise NotImplementedError

    def implied_probability(
        self,
        decimal_odds: Decimal,
        margin_adjust: bool = True,
    ) -> float:
        """Convert decimal odds to implied probability.

        Args:
            decimal_odds: Decimal odds (e.g., 3.50).
            margin_adjust: If True, apply a basic overround adjustment.

        Returns:
            Implied probability between 0 and 1.
        """
        if margin_adjust:
            return float(Decimal("1") / decimal_odds)
        return float(Decimal("1") / decimal_odds)

    def compare_to_model(
        self,
        model_predictions: dict[int, float],
        market_odds: list[dict[str, Any]],
    ) -> list[dict[str, Any]]:
        """Compare model probabilities to market-implied probabilities.

        Args:
            model_predictions: Dict of starter_id -> win_probability.
            market_odds: List of market odds dicts from get_race_odds.

        Returns:
            List of comparison dicts with keys:
            - starter_id: int | None
            - runner_name: str
            - model_prob: float
            - market_prob: float
            - edge: float (model - market, positive = value)
            - kelly_fraction: float | None
        """
        raise NotImplementedError

    async def clear_cache(self) -> None:
        """Clear the internal odds cache."""
        self._odds_cache.clear()
