"""
缓存管理模块

实现本地缓存机制，适配不同系统
"""

import json
import os
import platform
from typing import Any, Optional
from datetime import datetime, timedelta


class Cache:
    """
    缓存管理类
    
    用于缓存access_token等数据，避免重复调用接口
    """
    
    def __init__(self, cache_dir: Optional[str] = None):
        """
        初始化缓存管理
        
        :param cache_dir: 缓存目录路径，默认在用户目录下创建缓存文件夹
        """
        if cache_dir:
            self.cache_dir = cache_dir
        else:
            # 根据不同系统设置默认缓存目录
            system = platform.system()
            if system == "Windows":
                self.cache_dir = os.path.join(os.environ.get("APPDATA"), "xqcwechat", "cache")
            elif system == "Darwin":  # macOS
                self.cache_dir = os.path.join(os.environ.get("HOME"), "Library", "Caches", "xqcwechat")
            else:  # Linux
                self.cache_dir = os.path.join(os.environ.get("HOME"), ".cache", "xqcwechat")
        
        # 确保缓存目录存在
        os.makedirs(self.cache_dir, exist_ok=True)
    
    def _get_cache_file(self, key: str) -> str:
        """
        获取缓存文件路径
        
        :param key: 缓存键名
        :return: 缓存文件路径
        """
        return os.path.join(self.cache_dir, f"{key}.json")
    
    def set(self, key: str, value: Any, expires_in: int = 7200) -> None:
        """
        设置缓存
        
        :param key: 缓存键名
        :param value: 缓存值
        :param expires_in: 过期时间（秒），默认7200秒
        """
        cache_data = {
            "value": value,
            "expires_at": (datetime.now() + timedelta(seconds=expires_in)).isoformat()
        }
        
        cache_file = self._get_cache_file(key)
        with open(cache_file, "w", encoding="utf-8") as f:
            json.dump(cache_data, f, ensure_ascii=False, indent=2)
    
    def get(self, key: str) -> Optional[Any]:
        """
        获取缓存
        
        :param key: 缓存键名
        :return: 缓存值，如果缓存不存在或已过期则返回None
        """
        cache_file = self._get_cache_file(key)
        
        if not os.path.exists(cache_file):
            return None
        
        try:
            with open(cache_file, "r", encoding="utf-8") as f:
                cache_data = json.load(f)
            
            # 检查是否过期
            expires_at = datetime.fromisoformat(cache_data["expires_at"])
            if datetime.now() > expires_at:
                # 过期了，删除缓存文件
                os.remove(cache_file)
                return None
            
            return cache_data["value"]
        except Exception:
            # 读取缓存失败，删除缓存文件
            if os.path.exists(cache_file):
                os.remove(cache_file)
            return None
    
    def delete(self, key: str) -> None:
        """
        删除缓存
        
        :param key: 缓存键名
        """
        cache_file = self._get_cache_file(key)
        if os.path.exists(cache_file):
            os.remove(cache_file)
    
    def clear(self) -> None:
        """
        清空所有缓存
        """
        if os.path.exists(self.cache_dir):
            for file in os.listdir(self.cache_dir):
                if file.endswith(".json"):
                    os.remove(os.path.join(self.cache_dir, file))
