import json
import os
import time
import xbmcvfs

CACHE_DIR = xbmcvfs.translatePath("special://userdata/addon_data/plugin.video.jet_guide/ai_cache")
CACHE_FILE = os.path.join(CACHE_DIR, "responses.json")
USAGE_FILE = os.path.join(CACHE_DIR, "usage.json")

DEFAULT_CACHE_TTL = 86400  # 24 hours


def _ensure_cache_dir():
    if not os.path.exists(CACHE_DIR):
        os.makedirs(CACHE_DIR, exist_ok=True)


def _load_cache():
    _ensure_cache_dir()
    if os.path.exists(CACHE_FILE):
        try:
            with open(CACHE_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            return {}
    return {}


def _save_cache(cache):
    _ensure_cache_dir()
    try:
        with open(CACHE_FILE, 'w', encoding='utf-8') as f:
            json.dump(cache, f, indent=2)
    except IOError:
        pass


def get_cached(prompt_hash, ttl=None):
    if ttl is None:
        ttl = DEFAULT_CACHE_TTL
    cache = _load_cache()
    if prompt_hash in cache:
        entry = cache[prompt_hash]
        if time.time() - entry.get('time', 0) < ttl:
            return entry.get('response')
    return None


def set_cached(prompt_hash, response):
    cache = _load_cache()
    cache[prompt_hash] = {
        'response': response,
        'time': time.time()
    }
    _save_cache(cache)


def cleanup_cache(max_age=None):
    if max_age is None:
        max_age = DEFAULT_CACHE_TTL * 7  # 7 days
    cache = _load_cache()
    now = time.time()
    cleaned = {k: v for k, v in cache.items()
               if now - v.get('time', 0) < max_age}
    _save_cache(cleaned)


def get_usage():
    _ensure_cache_dir()
    if os.path.exists(USAGE_FILE):
        try:
            with open(USAGE_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            return {'date': '', 'count': 0}
    return {'date': '', 'count': 0}


def track_usage():
    from datetime import datetime
    usage = get_usage()
    today = datetime.now().strftime('%Y-%m-%d')
    if usage.get('date') != today:
        usage = {'date': today, 'count': 0}
    usage['count'] = usage.get('count', 0) + 1
    try:
        with open(USAGE_FILE, 'w', encoding='utf-8') as f:
            json.dump(usage, f, indent=2)
    except IOError:
        pass
    return usage['count']


def hash_prompt(prompt):
    import hashlib
    return hashlib.md5(prompt.encode('utf-8')).hexdigest()
