from typing import Optional, Any, Union
from datetime import datetime, timedelta, timezone
import os

# 导入配置
from app.core.config import config_handler

# 获取配置
JWT_SECRET_KEY = config_handler.get("admin_app", "JWT_SECRET_KEY", "dev-jwt-secret-key-change-in-production")
JWT_ALGORITHM = config_handler.get("admin_app", "ALGORITHM", "HS256")
ACCESS_TOKEN_EXPIRE_MINUTES = config_handler.get_int("admin_app", "ACCESS_TOKEN_EXPIRE_MINUTES", 30)

# 修复JWT导入 - 确保使用正确的JWT库
try:
    # 首先尝试使用PyJWT
    import jwt as pyjwt
    # 测试是否有encode方法
    test_token = pyjwt.encode({"test": "data"}, "secret", algorithm="HS256")
    jwt = pyjwt
    JWT_ERROR = (pyjwt.PyJWTError, pyjwt.DecodeError, pyjwt.ExpiredSignatureError)
    print("✅ 使用PyJWT库")
except (ImportError, AttributeError, TypeError) as e:
    print(f"PyJWT导入失败: {e}")
    try:
        # 尝试使用python-jose
        from jose import jwt, JWTError
        JWT_ERROR = (JWTError,)
        print("✅ 使用python-jose库")
    except ImportError as e:
        print(f"python-jose导入失败: {e}")
        # 最后尝试安装PyJWT
        print("尝试安装PyJWT...")
        import subprocess
        import sys
        try:
            subprocess.check_call([sys.executable, "-m", "pip", "install", "PyJWT"])
            import jwt
            JWT_ERROR = (jwt.PyJWTError, jwt.DecodeError, jwt.ExpiredSignatureError)
            print("✅ PyJWT安装成功")
        except Exception as install_error:
            print(f"❌ PyJWT安装失败: {install_error}")
            raise ImportError("无法导入JWT库，请手动安装: pip install PyJWT")


def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
    """
    创建访问令牌
    
    Args:
        data: 要编码的数据
        expires_delta: 过期时间增量
        
    Returns:
        str: JWT令牌
    """
    to_encode = data.copy()
    
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    
    to_encode.update({"exp": expire})
    
    encoded_jwt = jwt.encode(to_encode, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM)
    
    # PyJWT 2.0+ 返回字符串，旧版本返回bytes
    if isinstance(encoded_jwt, bytes):
        encoded_jwt = encoded_jwt.decode('utf-8')
    
    return encoded_jwt


def verify_token(token: str) -> Optional[dict]:
    """
    验证令牌
    
    Args:
        token: JWT令牌
        
    Returns:
        Optional[dict]: 解码后的payload，验证失败返回None
    """
    try:
        payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
        return payload
    except JWT_ERROR as e:
        print(f"Token验证失败: {e}")
        return None
    except Exception as e:
        print(f"Token验证异常: {e}")
        return None


def decode_token(token: str) -> Optional[dict]:
    """
    解码令牌（不验证签名）
    
    Args:
        token: JWT令牌
        
    Returns:
        Optional[dict]: 解码后的payload
    """
    try:
        # 不验证签名，仅解码
        payload = jwt.decode(token, options={"verify_signature": False})
        return payload
    except Exception as e:
        print(f"Token解码失败: {e}")
        return None
