"""
Flask context processors for RateRight Australian Construction Marketplace
Provides global template variables for navigation and UI components
"""
from flask import g
from flask_login import current_user
from .services.notification_service import notification_service


def inject_notification_counts():
    """
    Inject notification and message counts into all templates
    Used for navigation badges and UI indicators
    """
    if current_user.is_authenticated:
        try:
            # Get unread notification count
            unread_notifications_count = notification_service.get_unread_count(current_user.id)
            
            # TODO: Get unread message count when message service is implemented
            # For now, use a placeholder
            unread_messages_count = 0
            
            return {
                'unread_notifications_count': unread_notifications_count,
                'unread_messages_count': unread_messages_count
            }
        except Exception as e:
            # Fail gracefully - don't break templates if notification service fails
            print(f"[WARNING] Context processor failed: {e}")
            return {
                'unread_notifications_count': 0,
                'unread_messages_count': 0
            }
    else:
        # Not authenticated - no counts needed
        return {
            'unread_notifications_count': 0,
            'unread_messages_count': 0
        }


def inject_user_context():
    """
    Inject additional user context for templates
    """
    if current_user.is_authenticated:
        return {
            'current_user_role': current_user.role,
            'current_user_name': f"{current_user.first_name} {current_user.last_name}",
            'is_contractor': current_user.role in ['contractor', 'employer'],
            'is_worker': current_user.role == 'worker',
            'is_super_admin': current_user.role == 'super_admin'
        }
    else:
        return {
            'current_user_role': None,
            'current_user_name': None,
            'is_contractor': False,
            'is_worker': False,
            'is_super_admin': False
        }


def inject_app_globals():
    """
    Inject global application variables
    """
    return {
        'app_name': 'RateRight',
        'app_tagline': 'Australian Construction Marketplace',
        'current_year': 2024
    }


def format_job_duration(duration_value):
    """
    Format job duration for display.
    Handles both new numeric format (e.g., '8') and legacy formats (e.g., 'full_day', '2 days').
    
    Args:
        duration_value: String containing either a number or legacy format
        
    Returns:
        Formatted string with 'hours' appended for numeric values, or the legacy format as-is
    """
    if not duration_value:
        return 'Not specified'
    
    # Check if it's a numeric value (new format)
    try:
        hours = int(duration_value)
        return f"{hours} hours"
    except ValueError:
        # Legacy format - map to hours if possible, otherwise return as-is
        legacy_mapping = {
            'half_day': '4 hours',
            'full_day': '8 hours',
            'long_day': '10 hours',
            '2_days': '16 hours (2 days)',
            '3_5_days': '32 hours (3-5 days)',
            '1_week_plus': '40+ hours (1+ week)'
        }
        
        # Try to get mapped value
        mapped = legacy_mapping.get(duration_value)
        if mapped:
            return mapped
        
        # Otherwise, format the string nicely (replace underscores, title case)
        return duration_value.replace('_', ' ').title()
