from fastapi import Request, HTTPException, status
from typing import Any, Optional, Dict
import contextvars

current_user_var: contextvars.ContextVar[Optional[Dict[str, Any]]] = contextvars.ContextVar("current_user", default=None)

def get_current_user_info(request: Request) -> dict:
    """
    FastAPI dependency to retrieve the current user info attached by JWTAuthenticationMiddleware.
    """
    user_id = getattr(request.state, "user_id", None)
    role = getattr(request.state, "role", None)
    email = getattr(request.state, "email", None)
    
    if user_id:
        return {
            "user_id": user_id,
            "role": role,
            "email": email
        }
        
    # Check if this is a POST request (form submission) or GET pdf download request.
    is_post = request.method == "POST"
    is_download_pdf = request.method == "GET" and request.url.path.endswith("/download-pdf")
    
    if is_post or is_download_pdf:
        return {
            "user_id": None,
            "role": None,
            "email": None
        }
        
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Authentication is required. Please log in to continue."
    )

def verify_owner_or_admin(record: Any, current_user: dict):
    """
    Enforces role-based access control.
    Admins can access any record.
    Customers can only access records matching their user_id or email address.
    Anonymous users can access anonymous records (where user_id is None).
    """
    if not current_user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Authentication is required. Please log in to continue."
        )
        
    if current_user.get("role") == "admin":
        return

    record_user_id = getattr(record, "user_id", None)
    
    # If the record is anonymous and the visitor is anonymous
    if record_user_id is None and current_user.get("user_id") is None:
        return

    # If visitor is anonymous but the record belongs to a user
    if current_user.get("user_id") is None:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You do not have permission to access this resource."
        )

    # Check user_id first
    if record_user_id is not None:
        if record_user_id != current_user.get("user_id"):
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="You do not have permission to access this resource."
            )
        return

    # Check for email field in the record
    email_val = None
    for field in ["email_address", "email", "email_id"]:
        if hasattr(record, field):
            email_val = getattr(record, field)
            break
            
    if not email_val:
        # If record has no email field, deny access for safety
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You do not have permission to access this resource."
        )
        
    user_email = current_user.get("email")
    if not user_email or email_val.lower() != user_email.lower():
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="You do not have permission to access this resource."
        )