import os
import time
from django.conf import settings
from .models import Tenant
from .permissions import can_view_donations, can_edit_voter, get_user_role, can_view_volunteers, can_edit_volunteer, can_view_voters

def project_context(request):
    """
    Adds project-specific environment variables to the template context globally.
    """
    context = {
        "project_description": os.getenv("PROJECT_DESCRIPTION", ""),
        "project_image_url": os.getenv("PROJECT_IMAGE_URL", ""),
        # Used for cache-busting static assets
        "deployment_timestamp": int(time.time()),
        "GOOGLE_MAPS_API_KEY": getattr(settings, 'GOOGLE_MAPS_API_KEY', ''),
    }

    if request.user.is_authenticated:
        tenant_id = request.session.get('tenant_id')
        if tenant_id:
            tenant = Tenant.objects.filter(id=tenant_id).first()
            if tenant:
                context['can_view_donations'] = can_view_donations(request.user, tenant)
                context['can_edit_voter'] = can_edit_voter(request.user, tenant)
                context['can_view_voters'] = can_view_voters(request.user, tenant)
                context['can_view_volunteers'] = can_view_volunteers(request.user, tenant)
                context['can_edit_volunteer'] = can_edit_volunteer(request.user, tenant)
                context['user_role'] = get_user_role(request.user, tenant)
    
    return context
