"""
Context processors for global template variables
"""
from django.db.models import Q


def sidebar_counts(request):
    """
    Provide counts for sidebar badges.

    Returns counts for:
    - Active complaints
    - Pending feedback
    - Open PX actions
    - Provisional users (PX Admin only)
    """
    if not request.user.is_authenticated:
        return {}

    from apps.complaints.models import Complaint
    from apps.feedback.models import Feedback
    from apps.px_action_center.models import PXAction

    user = request.user

    # Filter based on user role and tenant_hospital
    if user.is_px_admin():
        # PX Admins use their selected hospital from session
        hospital = getattr(request, 'tenant_hospital', None)
        if hospital:
            complaint_count = Complaint.objects.filter(
                hospital=hospital,
                status__in=['open', 'in_progress']
            ).count()
            feedback_count = Feedback.objects.filter(
                hospital=hospital,
                status__in=['submitted', 'reviewed']
            ).count()
            action_count = PXAction.objects.filter(
                hospital=hospital,
                status__in=['open', 'in_progress']
            ).count()
        else:
            complaint_count = 0
            feedback_count = 0
            action_count = 0
        # Count provisional users for PX Admin
        from apps.accounts.models import User
        provisional_user_count = User.objects.filter(
            is_provisional=True,
            acknowledgement_completed=False
        ).count()
    elif user.hospital:
        complaint_count = Complaint.objects.filter(
            hospital=user.hospital,
            status__in=['open', 'in_progress']
        ).count()
        feedback_count = Feedback.objects.filter(
            hospital=user.hospital,
            status__in=['submitted', 'reviewed']
        ).count()
        action_count = PXAction.objects.filter(
            hospital=user.hospital,
            status__in=['open', 'in_progress']
        ).count()
        # provisional_user_count = 0
    else:
        complaint_count = 0
        feedback_count = 0
        action_count = 0

    return {
        'complaint_count': complaint_count,
        'feedback_count': feedback_count,
        'action_count': action_count,
        'current_hospital': getattr(request, 'tenant_hospital', None),
        'is_px_admin': request.user.is_authenticated and request.user.is_px_admin(),
    }


def hospital_context(request):
    """
    Provide current hospital context to templates.

    This ensures hospital information is available in the header for all pages.
    """
    if not request.user.is_authenticated:
        return {}

    hospital = getattr(request, 'tenant_hospital', None)

    return {
        'current_hospital': hospital,
        'is_px_admin': request.user.is_px_admin(),
        # 'provisional_user_count': provisional_user_count,
    }
