import time
from .os_utils import get_os_info
from django.conf import settings

def app_version(request):
    os_icon, os_name = get_os_info()
    page_gen_time = ''
    if hasattr(request, '_start_time') and request._start_time:
        elapsed = time.time() - request._start_time
        page_gen_time = f"{elapsed * 1000:.0f}ms"
    return {
        'APP_ENV': 'dev' if settings.DEBUG else 'prod',
        'GIT_COMMIT_HASH': getattr(settings, 'GIT_COMMIT_HASH', 'unknown'),
        'OS_ICON': os_icon,
        'OS_NAME': os_name,
        'PAGE_GEN_TIME': page_gen_time,
    }


def impersonation(request):
    """Expose the impersonation state for the UI (user-bar chip + menu).

    Reads the impersonator id stored in the session when a staff member is
    acting as another user.
    """
    from django.contrib.auth import get_user_model
    from django.core.exceptions import ObjectDoesNotExist
    from django.urls import reverse

    impersonator_id = request.session.get('impersonator_id')
    impersonator = None
    avatar_url = None
    if impersonator_id:
        impersonator = (
            get_user_model().objects.filter(pk=impersonator_id).first()
        )
        if impersonator is None:
            request.session.pop('impersonator_id', None)
        else:
            try:
                profile = impersonator.userprofile
            except ObjectDoesNotExist:
                profile = None
            if profile is not None and profile.avatar_id:
                avatar_url = reverse('library:file_request', args=[profile.avatar.uuid])
    return {
        'impersonating': impersonator is not None,
        'impersonator': impersonator,
        'impersonator_avatar_url': avatar_url,
    }