import os
import time

from .models import BusinessMembership

ACTIVE_BUSINESS_SESSION_KEY = 'trustforge_active_business_id'


def project_context(request):
    """
    Adds project-specific environment variables and active workspace context globally.
    """
    current_membership = None
    memberships = []
    if getattr(request, 'user', None) and request.user.is_authenticated:
        memberships = list(
            BusinessMembership.objects.select_related('business').filter(
                user=request.user,
                business__is_active=True,
            )
        )
        active_business_id = request.session.get(ACTIVE_BUSINESS_SESSION_KEY)
        current_membership = next((item for item in memberships if item.business_id == active_business_id), None)
        if current_membership is None and memberships:
            current_membership = memberships[0]

    return {
        'project_description': os.getenv('PROJECT_DESCRIPTION', ''),
        'project_image_url': os.getenv('PROJECT_IMAGE_URL', ''),
        'deployment_timestamp': int(time.time()),
        'current_membership': current_membership,
        'user_memberships': memberships,
    }
