from fastapi import Request
from loguru import logger
from starlette.types import ASGIApp, Receive, Scope, Send

from fastpluggy.core.auth.anonymous import FPAnonymousUser


class CurrentUserMiddleware:
    """Pure ASGI middleware — avoids the extra asyncio.Task that BaseHTTPMiddleware creates."""

    def __init__(self, app: ASGIApp):
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return

        request = Request(scope)

        from fastpluggy.fastpluggy import FastPluggy

        fast_pluggy: FastPluggy = request.app.state.fastpluggy
        try:
            if fast_pluggy.auth_manager:
                user = await fast_pluggy.auth_manager.authenticate(request)
            else:
                user = None
        except Exception as e:
            logger.exception(e)
            user = None

        request.state.current_user = user[1] if user else FPAnonymousUser()
        request.state.roles = user[0] if user else None
        if hasattr(fast_pluggy.auth_manager, 'get_user_menu_entries'):
            request.state.user_menu = fast_pluggy.auth_manager.get_user_menu_entries(request)
        else:
            request.state.user_menu = []

        await self.app(scope, receive, send)
