import time
import requests
import xbmc
import xbmcgui

from tools import debug_log
from sportsgrid_config import get_espn_site_sport


_NEWS_CACHE = {}
_CACHE_TTL_SECONDS = 300  # 5 minutes
_HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}


def _extract_image_url(headline):
    """Pick the best image URL from a headline object."""
    images = headline.get('images', []) or []
    for img in images:
        if img.get('type') == 'header' and img.get('url'):
            return img['url']
    for img in images:
        if img.get('url'):
            return img['url']
    return ''


def _format_headline(headline):
    """Convert a raw ESPN article into a simplified dict."""
    return {
        'headline': headline.get('headline', ''),
        'description': headline.get('description', ''),
        'image': _extract_image_url(headline),
        'published': headline.get('published', ''),
        'link': headline.get('links', {}).get('web', {}).get('href', '')
                       if isinstance(headline.get('links'), dict) else '',
    }


def fetch_sport_news(sport_code, timeout=8, max_items=5):
    """
    Fetch the latest ESPN HeadlineNews items for a sport.

    Args:
        sport_code: internal sport key (e.g. 'mlb', 'nba', 'premierleague')
        timeout: request timeout in seconds
        max_items: maximum number of headlines to return

    Returns:
        list of dicts with 'headline', 'description', 'image', 'published', 'link'
        (empty list if no news or on error)
    """
    sport_code = (sport_code or '').lower()
    if not sport_code:
        return []

    cache_key = f"{sport_code}:{max_items}"
    now = time.time()
    cached = _NEWS_CACHE.get(cache_key)
    if cached and (now - cached.get('timestamp', 0)) < _CACHE_TTL_SECONDS:
        debug_log(f"SportsNews: using cached news for {sport_code}", xbmc.LOGINFO)
        return cached.get('data', [])

    espn_path = get_espn_site_sport(sport_code)
    url = f"https://site.api.espn.com/apis/site/v2/{espn_path}/news"
    debug_log(f"SportsNews: fetching {url}", xbmc.LOGINFO)

    try:
        response = requests.get(url, headers=_HEADERS, timeout=timeout)
        response.raise_for_status()
        data = response.json()
    except Exception as e:
        debug_log(f"SportsNews: error fetching news for {sport_code}: {e}", xbmc.LOGERROR)
        return []

    articles = data.get('articles', []) if isinstance(data, dict) else []
    if not articles:
        debug_log(f"SportsNews: no articles for {sport_code}", xbmc.LOGWARNING)
        return []

    # Skip video-only highlight articles; they need different handling to play
    non_media = [a for a in articles if a.get('type') != 'Media']
    if not non_media:
        debug_log(f"SportsNews: only media highlight articles for {sport_code}", xbmc.LOGWARNING)
        return []

    # Prefer HeadlineNews, but keep fallback order intact
    headline_news = [a for a in non_media if a.get('type') == 'HeadlineNews']
    if headline_news:
        chosen = headline_news[:max_items]
    else:
        chosen = non_media[:max_items]

    result = [_format_headline(h) for h in chosen]
    _NEWS_CACHE[cache_key] = {'timestamp': now, 'data': result}
    debug_log(f"SportsNews: found {len(result)} headlines for {sport_code}", xbmc.LOGINFO)
    return result


def apply_news_to_window(window, sport_code, index=0):
    """
    Fetch news for sport_code and set Window properties for skin display.
    Sets the item at the supplied index (defaults to first item).
    Clears properties if no news is found.

    Returns:
        The full list of fetched news items so callers can rotate through them.
    """
    if not sport_code:
        for key in ('SportNewsHeadline', 'SportNewsDescription', 'SportNewsImage', 'SportNewsPublished'):
            window.setProperty(key, '')
        return []

    news_items = fetch_sport_news(sport_code)
    if news_items:
        item = news_items[index % len(news_items)]
        window.setProperty('SportNewsHeadline', item.get('headline', ''))
        window.setProperty('SportNewsDescription', item.get('description', ''))
        window.setProperty('SportNewsImage', item.get('image', ''))
        window.setProperty('SportNewsPublished', item.get('published', ''))
        debug_log(f"SportsNews: set headline for {sport_code}: {item.get('headline', '')[:60]}", xbmc.LOGINFO)
    else:
        for key in ('SportNewsHeadline', 'SportNewsDescription', 'SportNewsImage', 'SportNewsPublished'):
            window.setProperty(key, '')
    return news_items
