import json
import time
from typing import List, Dict, Any
from diona.project.storage.storage import get_storage_instance


class CookieManager:
    """通用Cookie管理类"""
    
    def __init__(self):
        """
        初始化Cookie管理器
        """
        self.storage = get_storage_instance()
    
    def load_cookies(self, spider_name: str) -> List[Dict[str, Any]]:
        """
        加载保存的cookie
        
        Args:
            spider_name: 爬虫名称
            
        Returns:
            cookie列表
        """
        relative_path = f"{spider_name}_cookies.json"
        
        content = self.storage.read("crawler", relative_path, storage_type="user")
        
        if not content:
            print(f"Cookie文件不存在: ~/.diona/user/crawler/{relative_path}")
            return []
        
        try:
            cookies = json.loads(content)
            
            # 检查cookie是否过期
            valid_cookies = []
            for cookie in cookies:
                if self._is_cookie_valid(cookie):
                    valid_cookies.append(cookie)
                else:
                    print(f"Cookie已过期: {cookie.get('name')}")
            
            print(f"成功加载 {len(valid_cookies)} 个cookie")
            return valid_cookies
        except Exception as e:
            print(f"加载cookie失败: {e}")
            return []
    
    def save_cookies(self, spider_name: str, cookies: List[Dict[str, Any]]) -> bool:
        """
        保存cookie
        
        Args:
            spider_name: 爬虫名称
            cookies: cookie列表
            
        Returns:
            是否保存成功
        """
        relative_path = f"{spider_name}_cookies.json"
        
        try:
            # 过滤出有效的cookie
            valid_cookies = []
            for cookie in cookies:
                if self._is_cookie_valid(cookie):
                    valid_cookies.append(cookie)
            
            content = json.dumps(valid_cookies, ensure_ascii=False, indent=2)
            success = self.storage.write("crawler", relative_path, content, storage_type="user")
            
            if success:
                print(f"成功保存 {len(valid_cookies)} 个cookie到 ~/.diona/user/crawler/{relative_path}")
            else:
                print(f"保存cookie失败")
            
            return success
        except Exception as e:
            print(f"保存cookie失败: {e}")
            return False
    
    def _is_cookie_valid(self, cookie: Dict[str, Any]) -> bool:
        """
        检查cookie是否有效
        
        Args:
            cookie: cookie字典
            
        Returns:
            cookie是否有效
        """
        # 检查cookie是否有过期时间
        if 'expires' in cookie:
            try:
                # 检查cookie是否过期
                expires = float(cookie['expires'])
                current_time = time.time()
                if expires < current_time:
                    return False
            except ValueError:
                pass
        
        # 检查cookie是否有必要的字段
        required_fields = ['name', 'value', 'domain', 'path']
        for field in required_fields:
            if field not in cookie:
                return False
        
        return True
    
    def cookie_file_exists(self, spider_name: str) -> bool:
        """
        检查cookie文件是否存在
        
        Args:
            spider_name: 爬虫名称
            
        Returns:
            cookie文件是否存在
        """
        relative_path = f"{spider_name}_cookies.json"
        return self.storage.exists("crawler", relative_path, storage_type="user")