import os
import json
import xbmc
import xbmcgui
import xbmcvfs
from datetime import datetime

def debug_log(msg, level=xbmc.LOGINFO):
    xbmc.log(f"[JET_GUIDE PVR_SPORT_SEARCH] {msg}", level)

CACHE_PATH = xbmcvfs.translatePath('special://home/userdata/addon_data/plugin.video.jet_guide/pvr_sport_search_cache.json')

class JetGuideCache:
    def __init__(self, cache_path=CACHE_PATH):
        self.cache_path = cache_path
        self._ensure_cache_file()

    def _ensure_cache_file(self):
        if not os.path.exists(self.cache_path):
            with open(self.cache_path, 'w') as f:
                json.dump([], f)

    def load(self):
        try:
            with open(self.cache_path, 'r') as f:
                items = json.load(f)
            debug_log(f"Loaded {len(items)} cache entries.")
            return items
        except Exception as e:
            debug_log(f"Error loading cache: {e}", xbmc.LOGERROR)
            return []

    def save(self, query, items):
        try:
            cache = self.load()
            entry = {
                'query': query,
                'items': items,
                'time': datetime.now().timestamp()
            }
            cache.append(entry)
            with open(self.cache_path, 'w') as f:
                json.dump(cache, f)
            debug_log(f"Saved cache entry for query: {query}")
        except Exception as e:
            debug_log(f"Error saving cache: {e}", xbmc.LOGERROR)

    def clear(self):
        try:
            with open(self.cache_path, 'w') as f:
                json.dump([], f)
            debug_log("Cache cleared.")
        except Exception as e:
            debug_log(f"Error clearing cache: {e}", xbmc.LOGERROR)

# Example usage:
if __name__ == '__main__':
    cache = JetGuideCache()
    # Save a test entry
    cache.save('test_query', [{'title': 'Test Game', 'sportjetextractors': [{'address': 'http://example.com/stream.m3u8'}]}])
    # Load cache
    items = cache.load()
    debug_log(f"Cache contents: {items}")
    # Clear cache
    cache.clear()
