#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
VWED.util 模块 - 工具函数
"""

import asyncio
from typing import Optional
from utils.logger import get_logger


class VWEDUtilModule:
    """VWED.util 模块 - 工具函数"""
    
    def __init__(self, script_id: str):
        self.script_id = script_id
        self.logger = get_logger(f"script.{script_id}.util")
    
    def sleep(self, seconds: float):
        """同步睡眠"""
        import time
        time.sleep(seconds)
    
    async def async_sleep(self, seconds: float):
        """异步睡眠"""
        await asyncio.sleep(seconds)
    
    def now(self) -> str:
        """获取当前时间"""
        from datetime import datetime
        return datetime.now().isoformat()
    
    def timestamp(self) -> float:
        """获取当前时间戳"""
        import time
        return time.time()
    
    def uuid(self) -> str:
        """生成UUID"""
        import uuid
        return str(uuid.uuid4())
    
    async def get_auth_token(self, username: str = "vwed", password: str = "vwed_123456") -> Optional[str]:
        """获取认证token
        
        Args:
            username: 用户名，默认为"vwed"
            password: 密码，默认为"vwed_123456"
            
        Returns:
            Optional[str]: 认证令牌，如果获取失败则返回None
        """
        try:
            from services.sync_service import get_login_token
            token = await get_login_token(username, password)
            if token:
                self.logger.info(f"脚本 {self.script_id} 成功获取登录token")
                return token
            else:
                self.logger.warning(f"脚本 {self.script_id} 获取登录token失败")
                return None
        except Exception as e:
            self.logger.error(f"脚本 {self.script_id} 获取token异常: {str(e)}")
            return None
    
    async def refresh_token_if_needed(self) -> Optional[str]:
        """根据需要刷新token
        
        Returns:
            Optional[str]: 有效的认证令牌，如果获取失败则返回None
        """
        try:
            from services.sync_service import refresh_token_if_needed
            token = await refresh_token_if_needed()
            if token:
                self.logger.info(f"脚本 {self.script_id} 成功刷新token")
                return token
            else:
                self.logger.warning(f"脚本 {self.script_id} 刷新token失败")
                return None
        except Exception as e:
            self.logger.error(f"脚本 {self.script_id} 刷新token异常: {str(e)}")
            return None
    
    def clear_cached_token(self) -> None:
        """清除缓存的token"""
        try:
            from services.sync_service import clear_cached_token
            clear_cached_token()
            self.logger.info(f"脚本 {self.script_id} 成功清除缓存token")
        except Exception as e:
            self.logger.error(f"脚本 {self.script_id} 清除缓存token异常: {str(e)}")