# src/cchl_managers.py
import logging
from typing import Any, Dict, Optional, List
import json
import time
import requests
from datetime import datetime, timezone, date

from src.base_classes.hockey import Hockey, HockeyLive
from src.base_classes.sports import SportsRecent, SportsUpcoming
from src.cache_manager import CacheManager
from src.display_manager import DisplayManager

LOCAL_CCHL_FILE = "data/cchl_scoreboard.json"
LOCAL_CCHL_STANDINGS = "data/cchl_standings.json"

class BaseCCHLManager(Hockey):
    """Base class for CCHL managers; renders scoreboard and supplies leaderboard data."""
    def __init__(self, config: Dict[str, Any], display_manager: DisplayManager, cache_manager: CacheManager):
        self.logger = logging.getLogger('CCHL')
        super().__init__(config=config, display_manager=display_manager, cache_manager=cache_manager,
                         logger=self.logger, sport_key="cchl")
        self.league = "cchl"
        # CCHL specifics used for leaderboard data
        self.conferences: List[str] = ["yates", "robinson"]  # adjust to actual division names
        self.league_logo_path: str = "assets/sports/cchl_logos/CCHL.png"
        self._cached_standings: Optional[Dict[str, List[Dict[str, Any]]]] = None

    # ---------- Leaderboard data providers ----------
    def standings_provider(self) -> Dict[str, List[Dict[str, Any]]]:
        """Read local standings JSON and return {division: [teams...]}. Called by LeaderboardManager."""
        try:
            with open(LOCAL_CCHL_STANDINGS, "r") as f:
                data = json.load(f)
            return {
                "yates": data.get("yates", []),
                "robinson": data.get("robinson", []),
            }
        except Exception as e:
            self.logger.error(f"Failed to load CCHL standings JSON: {e}")
            return {"yates": [], "robinson": []}

    def get_league_data(self) -> Dict[str, Any]:
        """Return all static and dynamic data the generic LeaderboardManager needs."""
        return {
            "conferences": self.conferences,
            "league_logo": self.league_logo_path,
            "standings_provider": self.standings_provider,
        }

    # ---------- Scoreboard methods ----------
    def _build_url(self):
        today = date.today().strftime("%Y-%m-%d")
        return (
            "https://lscluster.hockeytech.com/feed/index.php"
            f"?feed=statviewfeed&view=schedule_day&date={today}"
            "&site_id=2&key=1defb601c9b37c24&client_code=cchl"
            "&league_id=1&season_id=110&conference_id=undefined"
            "&division_id=-1&team=-1&lang=en&forceDate=true"
            "&useSeason=false&allLeagues=0"
        )

    def fetch_games(self):
        url = self._build_url()
        try:
            raw = requests.get(url, timeout=10).text
            if raw.startswith("angular.callbacks"):
                raw = raw[raw.find("(")+1 : raw.rfind(")")]
            data = json.loads(raw)
            return data.get("games", [])
        except Exception as e:
            self.logger.error(f"[CCHL] Failed to fetch games: {e}")
            return []

    def parse_record(self, team):
        ot = int(team.get("solosses", 0)) + int(team.get("otlosses", 0))
        return f"{team.get('wins',0)}-{team.get('losses',0)}-{ot}"

    def _fetch_local_data(self):
        try:
            with open(LOCAL_CCHL_FILE, "r") as f:
                return json.load(f)
        except Exception as e:
            self.logger.error(f"Failed to load local CCHL scoreboard JSON: {e}")
            return None

    def _fetch_data(self, date_str: str = None):
        return self._fetch_local_data()

    def _load_standings_records(self):
        try:
            with open(LOCAL_CCHL_STANDINGS, "r") as f:
                standings = json.load(f)
            lookup = {}
            for div in self.conferences:
                for team in standings.get(div, []):
                    abbr = team.get("abbreviation")
                    rec = team.get("record")
                    if abbr and rec:
                        lookup[abbr] = rec
            return lookup
        except Exception as e:
            self.logger.warning(f"Could not load CCHL standings records: {e}")
            return {}

    def _extract_game_details(self, game_event: Dict) -> Optional[Dict]:
        details, home_team, away_team, status, situation = (
            self._extract_game_details_common(game_event)
        )
        if not details:
            return None
        try:
            if not hasattr(self, "_standings_lookup"):
                self._standings_lookup = self._load_standings_records()

            home_abbr = home_team["team"]["abbreviation"]
            away_abbr = away_team["team"]["abbreviation"]

            details.update({
                "home_score": home_team.get("score", "0"),
                "away_score": away_team.get("score", "0"),
                "home_logo_path": self.logo_dir / f"{home_abbr}.png",
                "away_logo_path": self.logo_dir / f"{away_abbr}.png",
                "status_text": status["type"]["shortDetail"],
                "home_record": self._standings_lookup.get(home_abbr, "0-0-0"),
                "away_record": self._standings_lookup.get(away_abbr, "0-0-0"),
            })
            return details
        except Exception as e:
            self.logger.error(f"CCHL extract error: {e}")
            return None

# --- Concrete Managers ---
class CCHLLiveManager(BaseCCHLManager, HockeyLive):
    def __init__(self, config, display_manager, cache_manager):
        super().__init__(config, display_manager, cache_manager)
        self.logger = logging.getLogger('CCHLLiveManager')

class CCHLRecentManager(BaseCCHLManager, SportsRecent):
    def __init__(self, config, display_manager, cache_manager):
        super().__init__(config, display_manager, cache_manager)
        self.logger = logging.getLogger('CCHLRecentManager')

class CCHLUpcomingManager(BaseCCHLManager, SportsUpcoming):
    def __init__(self, config, display_manager, cache_manager):
        super().__init__(config, display_manager, cache_manager)
        self.logger = logging.getLogger('CCHLUpcomingManager')

    def _fetch_data(self, date_str: str = None):
        data = super()._fetch_data(date_str)
        if not data:
            return None

        now = datetime.now(timezone.utc)
        future_events = []
        for e in data.get("events", []):
            try:
                dt = datetime.strptime(e["date"], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
                if dt >= now:
                    future_events.append((dt, e))
            except Exception as ex:
                self.logger.warning(f"Skipping event with bad date: {ex}")

        future_events.sort(key=lambda x: x[0])
        data["events"] = [e for _, e in future_events]
        return data
