import requests
from .exceptions import RimbleAPIError

VALID_SPORTS = ('lol', 'csgo', 'dota2', 'valorant', 'rocketleague', 'cod', 'nba2k', 'fifa', 'siege', 'cricket')
DEFAULT_BASE_URL = 'https://rimbleanalytics.com'


class RimbleClient:
    """Client for the Rimble Raw Data API."""

    def __init__(self, api_key, base_url=DEFAULT_BASE_URL):
        self.api_key = api_key
        self.base_url = base_url.rstrip('/')
        self.session = requests.Session()
        self.session.headers.update({'x-api-key': api_key})

    def _request(self, sport, endpoint, **params):
        if sport not in VALID_SPORTS:
            raise ValueError(f"Invalid sport '{sport}'. Must be one of: {', '.join(VALID_SPORTS)}")
        url = f"{self.base_url}/raw/{sport}/{endpoint}/"
        resp = self.session.get(url, params=params or None)
        if resp.status_code != 200:
            raise RimbleAPIError(resp.status_code, response=resp)
        return resp.json()

    def get_upcoming_matches(self, sport, **params):
        """Get upcoming matches. Params: date, matchid, time, team, league."""
        return self._request(sport, 'upcoming-matches', **params)

    def get_live_matches(self, sport, **params):
        """Get live matches. Params: date, matchid, time, team, league."""
        return self._request(sport, 'live-matches', **params)

    def get_completed_matches(self, sport, **params):
        """Get completed matches (last 5 days). Params: date, matchid, time, team, league."""
        return self._request(sport, 'completed-matches', **params)

    def get_match_status(self, sport, matchid, **params):
        """Get match status. Returns: upcoming, live, ended, completed, or cancelled."""
        return self._request(sport, 'match-status', matchid=matchid, **params)

    def get_league_mappings(self, sport, **params):
        """Get league/tournament mappings. Params: league_id, name, min_prize_money."""
        return self._request(sport, 'league-mappings', **params)

    def get_teams(self, sport, **params):
        """Get teams. Params: id."""
        return self._request(sport, 'teams', **params)

    def get_players(self, sport, **params):
        """Get players. Params: id."""
        return self._request(sport, 'players', **params)
