from django.conf import settings


def app_context(request):
    user = getattr(request, "user", None)
    authenticated = getattr(user, "is_authenticated", False)
    agency = getattr(request, "agency", None)
    context = {
        "app_name": "Fablabs Manager",
        "current_agency": agency,
        "nav_theme": getattr(user, "theme", "system") if authenticated else "system",
        "debug": settings.DEBUG,
    }
    if not authenticated:
        return context

    from apps.communications.models import Notification
    from apps.sync.models import OutboxEvent

    from .navigation import construire

    pending = 0
    if agency:
        pending = OutboxEvent.objects.filter(
            agency_id=agency.id, status__in=["PENDING", "FAILED", "DEFERRED"]
        ).count()
    context.update({
        "unread_notifications": Notification.objects.filter(recipient=user, read_at__isnull=True).count(),
        "user_agencies": user.agencies_for_switch(),
        "pending_sync": pending,
        "nav_sections": construire(request),
        "user_role_label": (user.roles[0].name_fr if user.roles else ("Super administrateur" if user.is_superuser else "Membre")),
    })
    return context
