import os
import json
import time
import hashlib

panelPath = os.getenv('BT_PANEL')
if not panelPath:
    panelPath = "/www/server/panel"

class FileCache:

    def __init__(self,):
        """
        初始化文件缓存
        @param cache_dir: 缓存目录
        """
        self.cache_dir = os.path.join(panelPath, "data", "cache")
        if not os.path.exists(self.cache_dir):
            os.makedirs(self.cache_dir)

    def _get_cache_path(self, key):
        """
        根据 key 生成缓存文件路径
        @param key: 缓存键
        @return: 缓存文件路径
        """
        hashed_key = hashlib.md5(key.encode("utf-8")).hexdigest()
        return os.path.join(self.cache_dir, f"{hashed_key}.json")

    def set(self, key, value, timeout=None):
        """
        设置缓存
        @param key: 缓存键
        @param value: 缓存值
        @param timeout: 超时时间（秒），默认无限制
        """
        cache_data = {
            "value": value,
            "expire_at": time.time() + timeout if timeout else None
        }
        cache_path = self._get_cache_path(key)
        with open(cache_path, "w", encoding="utf-8") as f:
            json.dump(cache_data, f)

    def get(self, key):
        """
        获取缓存
        @param key: 缓存键
        @return: 缓存值，如果不存在或已过期返回 None
        """
        cache_path = self._get_cache_path(key)
        if not os.path.exists(cache_path):
            return None

        with open(cache_path, "r", encoding="utf-8") as f:
            cache_data = json.load(f)

        # 检查是否过期
        if cache_data["expire_at"] and time.time() > cache_data["expire_at"]:
            self.delete(key)
            return None

        return cache_data["value"]

    def delete(self, key):
        """
        删除缓存
        @param key: 缓存键
        """
        cache_path = self._get_cache_path(key)
        if os.path.exists(cache_path):
            os.remove(cache_path)

    def clear(self):
        """
        清空所有缓存
        """
        for filename in os.listdir(self.cache_dir):
            file_path = os.path.join(self.cache_dir, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)


