"""
CMS context processors — injected into every CMS template automatically.
"""
from django.utils import timezone


def cms_notifications(request):
    """
    Inject notification counts (new items since last dismissed / last login)
    into every CMS page.
    """
    if not request.path.startswith('/cms/'):
        return {}
    if not getattr(request, 'user', None) or not request.user.is_authenticated:
        return {}

    # Use session-based dismiss time if available, else fall back to last_login
    cleared_str = request.session.get('notif_cleared_at')
    if cleared_str:
        try:
            from datetime import datetime
            since = datetime.fromisoformat(cleared_str)
            # Make timezone-aware if naive
            if since.tzinfo is None:
                from django.utils.timezone import make_aware
                since = make_aware(since)
        except Exception:
            since = None
    else:
        since = None

    if since is None:
        since = request.user.last_login or timezone.now().replace(
            hour=0, minute=0, second=0, microsecond=0
        )

    notifications = []

    try:
        from apps.tickets.models import Ticket
        # Ticket.inbox() is what /cms/tickets/ lists. Counting every row here
        # instead was reporting closed, resolved and blocked-sender tickets as
        # new, so the badge sent you to an empty inbox.
        count = Ticket.inbox().filter(created_at__gt=since).count()
        if count:
            notifications.append({
                'icon': 'fa-ticket',
                'label': f'{count} new ticket{"s" if count != 1 else ""}',
                'url': '/cms/tickets/',
                'colour': '#3b82f6',
            })
    except Exception:
        pass

    try:
        from apps.sales.models import ProjectAssessment
        # Same trap as tickets: the list hides archived rows and shows only
        # this tenant's, so the badge has to do both or it counts rows that
        # are not there when you arrive.
        assessments = ProjectAssessment.objects.filter(is_archived=False)
        tenant = getattr(request, 'tenant', None)
        if tenant is not None and getattr(tenant, 'pk', 0):
            assessments = assessments.filter(tenant=tenant)
        count = assessments.filter(created_at__gt=since).count()
        if count:
            notifications.append({
                'icon': 'fa-file-circle-check',
                'label': f'{count} new assessment{"s" if count != 1 else ""}',
                'url': '/cms/assessments/',
                'colour': '#d97706',
            })
    except Exception:
        pass

    try:
        from apps.ecommerce.models import Order
        count = Order.objects.filter(created_at__gt=since).count()
        if count:
            notifications.append({
                'icon': 'fa-bag-shopping',
                'label': f'{count} new order{"s" if count != 1 else ""}',
                'url': '/cms/orders/',
                'colour': '#22c55e',
            })
    except Exception:
        pass

    return {
        'cms_notifications': notifications,
        'cms_notifications_since': since,
    }


def role_permissions(request):
    """
    Expose the current user's sections to every CMS template, so the sidebar can
    hide what this role cannot open. Enforcement lives in the middleware; this is
    only about not showing people doors they cannot walk through.
    """
    user = getattr(request, 'user', None)
    if not user or not user.is_authenticated:
        return {}
    from apps.accounts.permissions import sections_for, is_read_only
    sections = sections_for(user)
    return {
        'can_section': {key: True for key in sections},
        'is_read_only_role': is_read_only(user),
    }
