import httpx
from fastapi import Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import EmailStr
from starlette import status

from ..models.responses.models import NakamaJWTResponse
from ..models.settings.cluster import WorkerConfig

config = WorkerConfig()

bearer_scheme = HTTPBearer(scheme_name="bearer", description="固定API Token的鉴权方式", auto_error=True)


async def verify_token(credentials: HTTPAuthorizationCredentials = Depends(bearer_scheme)):
    token = credentials.credentials
    # 在这里实现你的token验证逻辑
    if not is_valid_token(token):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid authentication credentials",
            headers={"WWW-Authenticate": "Bearer"},
        )
    return token


def is_valid_token(token: str) -> bool:
    #
    if token == config.api_server_token:
        return True
    else:
        response = httpx.get(url=f"{config.nakama_client_endpoint}/v2/account",
                             headers={"Authorization": f"Bearer {token}"})
        return response.is_success


def nakama_login(email: EmailStr, password: str) -> NakamaJWTResponse:
    response = httpx.post(url=f"{config.nakama_client_endpoint}/v2/account/authenticate/email",
                          json={"email": email.__str__(), "password": password, "create": False})
    response.raise_for_status()
    return NakamaJWTResponse.model_validate_json(response.text)
