# middleware/frontend_type.py
"""
Frontend Type Detection Middleware

Sets request.state.frontend_type for all requests using centralized FrontendDetector.

This middleware replaces the old ContextMiddleware and provides a unified way to
detect which frontend (ADMIN, VENDOR, STOREFRONT, PLATFORM) is being accessed.

MUST run AFTER VendorContextMiddleware to have access to vendor context.
MUST run BEFORE LanguageMiddleware (which needs frontend_type).

Sets:
    request.state.frontend_type: FrontendType enum value
"""

import logging

from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware

from app.core.frontend_detector import FrontendDetector
from app.modules.enums import FrontendType

logger = logging.getLogger(__name__)


class FrontendTypeMiddleware(BaseHTTPMiddleware):
    """
    Middleware to detect and inject frontend type into request state.

    Uses FrontendDetector for centralized, consistent detection across the app.

    Runs AFTER VendorContextMiddleware in request chain.
    Depends on:
        request.state.vendor (optional, set by VendorContextMiddleware)
        request.state.clean_path (optional, set by VendorContextMiddleware)

    Sets:
        request.state.frontend_type: FrontendType enum value
    """

    async def dispatch(self, request: Request, call_next):
        """Detect frontend type and inject into request state."""
        host = request.headers.get("host", "")
        # Use clean_path if available (from vendor_context_middleware), else original path
        path = getattr(request.state, "clean_path", None) or request.url.path

        # Check if vendor context exists (set by VendorContextMiddleware)
        has_vendor_context = (
            hasattr(request.state, "vendor")
            and request.state.vendor is not None
        )

        # Detect frontend type using centralized detector
        frontend_type = FrontendDetector.detect(
            host=host,
            path=path,
            has_vendor_context=has_vendor_context,
        )

        # Store in request state
        request.state.frontend_type = frontend_type

        # Log detection for debugging
        logger.debug(
            f"[FRONTEND_TYPE_MIDDLEWARE] Frontend type detected: {frontend_type.value}",
            extra={
                "path": request.url.path,
                "clean_path": getattr(request.state, "clean_path", "NOT SET"),
                "host": host,
                "frontend_type": frontend_type.value,
                "has_vendor": has_vendor_context,
            },
        )

        # Continue processing
        response = await call_next(request)
        return response


def get_frontend_type(request: Request) -> FrontendType:
    """
    Helper function to get current frontend type from request.

    Args:
        request: FastAPI request object

    Returns:
        FrontendType enum value (defaults to PLATFORM if not set)
    """
    return getattr(request.state, "frontend_type", FrontendType.PLATFORM)
