"""
Bet9ja scraper.

HOW TO FIND THE ENDPOINTS (required — their API isn't accessible via simple requests):
───────────────────────────────────────────────────────────────────────────────────────
1. Open https://sports.bet9ja.com in Chrome
2. Press F12 → Network tab → click "Fetch/XHR"
3. Wait for the football section to fully load (may take 10-20 sec)
4. Look for requests returning JSON with odds/events data
5. Right-click → Copy → Copy as cURL
6. Paste the URL and any required headers below

What to look for in the Network tab:
  - Requests to external domains (their API is likely not on sports.bet9ja.com itself)
  - JSON responses containing fields like: eventId, homeTeam, awayTeam, odds, markets
  - Look for repeated requests that update when odds change

Once you find the endpoint:
  1. Update BASE_URL and ENDPOINTS below
  2. Add any required headers to the session in __init__
  3. Implement _parse() based on the actual response structure
───────────────────────────────────────────────────────────────────────────────────────
"""
import logging
from datetime import datetime
from typing import List

from scrapers.base import BaseScraper
from core.models import Event, Outcome

logger = logging.getLogger(__name__)


# ── UPDATE THESE ─────────────────────────────────────────────────────────────
BASE_URL = ""   # e.g. "https://api.bet9ja.com"

SPORT_ENDPOINTS = {
    'football':   "",   # e.g. "/api/v1/football/events"
    'basketball': "",
    'tennis':     "",
}

REQUIRED_HEADERS = {
    # Add headers from DevTools here, e.g.:
    # "x-api-key": "...",
    # "authorization": "Bearer ...",
}
# ─────────────────────────────────────────────────────────────────────────────


class Bet9jaScraper(BaseScraper):

    def __init__(self):
        super().__init__('Bet9ja')
        if REQUIRED_HEADERS:
            self.session.headers.update(REQUIRED_HEADERS)

    def get_events(self, sport: str) -> List[Event]:
        endpoint = SPORT_ENDPOINTS.get(sport, "")
        if not BASE_URL or not endpoint:
            # Silently skip — not yet configured
            return []

        try:
            url = BASE_URL + endpoint
            resp = self.session.get(url, timeout=15)
            resp.raise_for_status()
            return self._parse(resp.json(), sport)
        except Exception as ex:
            logger.warning(f"[Bet9ja] {sport} fetch failed: {ex}")
            return []

    def _parse(self, data: dict, sport: str) -> List[Event]:
        """
        Parse Bet9ja API response into Event objects.
        UPDATE this once you have a real response to inspect.

        Typical structure to look for:
          - event ID, home team name, away team name
          - start time (Unix timestamp or ISO string)
          - markets with outcomes and odds

        Example template:
            events_raw = data.get('events', [])
            for raw in events_raw:
                home = raw['homeTeam']
                away = raw['awayTeam']
                for market in raw.get('markets', []):
                    outcomes = [
                        Outcome(name=o['name'], odds=float(o['odds']), bookmaker='Bet9ja')
                        for o in market.get('selections', [])
                        if float(o.get('odds', 0)) > 1.0
                    ]
                    ...
        """
        return []
