import logging
from typing import Optional, Dict

logger = logging.getLogger(__name__)

class TokenReader:
    """Token文件读取器"""
    
    def __init__(self, token_path: str):
        self.token_path = token_path
        self._tokens: Optional[Dict[str, str]] = None
    
    def _load_tokens(self) -> Dict[str, str]:
        """加载token文件"""
        if self._tokens is not None:
            return self._tokens
        
        tokens = {}
        try:
            with open(self.token_path, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith('#') and '=' in line:
                        key, value = line.split('=', 1)
                        tokens[key.strip()] = value.strip()
            
            self._tokens = tokens
            logger.info(f"成功加载 {len(tokens)} 个token")
            
        except Exception as e:
            logger.error(f"读取token文件失败: {e}")
            raise
        
        return tokens
    
    def get_token(self, key: str) -> Optional[str]:
        """获取指定的token"""
        tokens = self._load_tokens()
        return tokens.get(key)
    
    def get_all_tokens(self) -> Dict[str, str]:
        """获取所有tokens"""
        return self._load_tokens().copy()
    
    def reload(self):
        """重新加载token文件"""
        self._tokens = None
        logger.info("Token文件已重新加载")