"""
Utility functions for checking stamp permissions based on supervisor groups.
"""
from user.models import User
from userSettings.models import UserSettings
from supervisor.models import Supervisor


def get_user_stamp_permissions(user_id):
    """
    Get stamp permissions for a user based on their supervisor_code.
    
    Returns a dict with:
    - can_add_stamps: bool
    - can_edit_stamps: bool
    - can_delete_stamps: bool
    
    If user has no supervisor_code or supervisor not found, defaults to True (allow all).
    """
    try:
        # Get user settings to find supervisor_code
        try:
            user_settings = UserSettings.objects.get(user_id=user_id)
            supervisor_code = user_settings.supervisor_code
        except UserSettings.DoesNotExist:
            # No settings found, default to allow all
            return {
                'can_add_stamps': True,
                'can_edit_stamps': True,
                'can_delete_stamps': True
            }
        
        if not supervisor_code:
            # No supervisor code assigned, default to allow all
            return {
                'can_add_stamps': True,
                'can_edit_stamps': True,
                'can_delete_stamps': True
            }
        
        # Find supervisor by code
        try:
            supervisor = Supervisor.objects.get(code=supervisor_code)
            return {
                'can_add_stamps': supervisor.can_add_stamps,
                'can_edit_stamps': supervisor.can_edit_stamps,
                'can_delete_stamps': supervisor.can_delete_stamps
            }
        except Supervisor.DoesNotExist:
            # Supervisor not found, default to allow all
            return {
                'can_add_stamps': True,
                'can_edit_stamps': True,
                'can_delete_stamps': True
            }
    except Exception as e:
        # On any error, default to allow all (fail open)
        return {
            'can_add_stamps': True,
            'can_edit_stamps': True,
            'can_delete_stamps': True
        }


def check_stamp_permission(user_id, permission_type):
    """
    Check if a user has a specific stamp permission.
    
    Args:
        user_id: UUID of the user
        permission_type: 'add', 'edit', or 'delete'
    
    Returns:
        bool: True if permission is granted, False otherwise
    """
    permissions = get_user_stamp_permissions(user_id)
    
    if permission_type == 'add':
        return permissions['can_add_stamps']
    elif permission_type == 'edit':
        return permissions['can_edit_stamps']
    elif permission_type == 'delete':
        return permissions['can_delete_stamps']
    else:
        # Unknown permission type, default to False (fail closed)
        return False

