from typing import Any

from fastapi import HTTPException, status, Request
from .user_auth_schemas import UserAuthResponse
from test_infinity_stones.network_router import HttpRequest, APIAuth, HttpMethod, NetworkRouter
from test_infinity_stones.config import Settings
import logging

logger = logging.getLogger()

class Authenticator:
    def __init__(self, settings: Settings, network_router: NetworkRouter = NetworkRouter()):
        self._settings = settings
        self._network_router = network_router


    async def authenticate_user(self, request: Request) -> None:
        authorization = request.headers.get("Authorization")

        if not authorization:
            raise HTTPException(status_code=401)

        split_auth_header = authorization.split(" ")

        if len(split_auth_header) < 2:
            raise HTTPException(status_code=401)

        access_token = split_auth_header[1]

        user_auth_response = await self.get_user_details(access_token)
        print("User Auth Response:", user_auth_response)
        user_id = user_auth_response.identity.id

        request.state.user_id = user_id
        # TODO: Add access scopes to request state

        print('User ID In Middleware:', user_id)

    async def get_user_details(self, access_token: str) -> UserAuthResponse:
        request = HttpRequest[Any](
            method=HttpMethod.GET,
            base_url=self._settings.AUTH_SERVICE_BASE_URL,
            path=self._settings.AUTHENTICATE_USER_ENDPOINT_PATH,
            headers=APIAuth.bearer(access_token),
        )

        try:
            response = await self._network_router.execute_http_request(request)

            if response.status_code != 200:
                raise HTTPException(status_code=401, detail=response.body)

        except Exception as e:
            logger.error(f"Error while authenticating user {e}")
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)

        return UserAuthResponse(**response.body)