"""
用户偏好存储 - 记住用户偏好和查询历史
"""
import json
from pathlib import Path
from typing import Dict, Optional
import time

class UserPreference:
    """用户偏好管理"""

    def __init__(self, storage_path: str = None):
        if storage_path:
            self.storage_path = Path(storage_path)
        else:
            self.storage_path = Path(__file__).parent.parent / "data" / "user_prefs.json"
        
        self.storage_path.parent.mkdir(parents=True, exist_ok=True)
        self._cache = self._load()

    def _load(self) -> Dict:
        """加载存储"""
        if self.storage_path.exists():
            try:
                return json.loads(self.storage_path.read_text())
            except:
                return {"users": {}}
        return {"users": {}}

    def _save(self):
        """保存存储"""
        self.storage_path.write_text(json.dumps(self._cache, ensure_ascii=False, indent=2))

    def get_last_query(self, user_id: str = "default") -> Optional[Dict]:
        """获取用户上次查询"""
        return self._cache.get("users", {}).get(user_id, {}).get("last_query")

    def set_last_query(self, query: Dict, user_id: str = "default"):
        """设置用户上次查询"""
        if "users" not in self._cache:
            self._cache["users"] = {}
        if user_id not in self._cache["users"]:
            self._cache["users"][user_id] = {}
        
        self._cache["users"][user_id]["last_query"] = {
            **query,
            "timestamp": time.time()
        }
        self._save()

    def add_shown_gift(self, gift_name: str, user_id: str = "default"):
        """记录已展示的礼物（用于换一个功能）"""
        if "users" not in self._cache:
            self._cache["users"] = {}
        if user_id not in self._cache["users"]:
            self._cache["users"][user_id] = {}
        
        shown = self._cache["users"][user_id].get("shown_gifts", [])
        shown.append(gift_name)
        # 只保留最近20个
        self._cache["users"][user_id]["shown_gifts"] = shown[-20:]
        self._save()

    def get_shown_gifts(self, user_id: str = "default") -> list:
        """获取已展示的礼物"""
        return self._cache.get("users", {}).get(user_id, {}).get("shown_gifts", [])

    def clear_shown_gifts(self, user_id: str = "default"):
        """清空已展示记录"""
        if user_id in self._cache.get("users", {}):
            self._cache["users"][user_id]["shown_gifts"] = []
            self._save()


# 全局实例（简单实现，实际应使用依赖注入）
_global_preference = None

def get_preference() -> UserPreference:
    """获取全局偏好实例"""
    global _global_preference
    if _global_preference is None:
        _global_preference = UserPreference()
    return _global_preference
