from django.conf import settings
from firebase_admin import messaging


def send_fcm_notification(fcm_token, title, message, data=None):
    """
    Send FCM notification using Firebase Admin SDK (HTTP v1 API)
    This is the recommended method and works with the new FCM API
    """
    if not fcm_token:
        return False
    
    # Check if Firebase is initialized
    if not hasattr(settings, 'FIREBASE_APP') or settings.FIREBASE_APP is None:
        print('Firebase not initialized. Check service account file.')
        return False
    
    try:
        # Build the message using Firebase Admin SDK
        notification = messaging.Notification(
            title=title,
            body=message,
        )
        
        # Convert data dict to proper format (all values must be strings)
        message_data = {}
        if data:
            message_data = {str(k): str(v) for k, v in data.items()}
        
        # Create the message
        message_obj = messaging.Message(
            notification=notification,
            data=message_data,
            token=fcm_token,
            android=messaging.AndroidConfig(
                priority='high',
            ),
            apns=messaging.APNSConfig(
                headers={'apns-priority': '10'},
                payload=messaging.APNSPayload(
                    aps=messaging.Aps(sound='default'),
                ),
            ),
        )
        
        # Send the message
        response = messaging.send(message_obj)
        print(f'Successfully sent FCM message: {response}')
        return True
        
    except messaging.UnregisteredError:
        print(f'FCM token is unregistered: {fcm_token}')
        return False
    except messaging.SenderIdMismatchError:
        print('FCM sender ID mismatch')
        return False
    except messaging.InvalidArgumentError as e:
        print(f'FCM invalid argument: {e}')
        return False
    except Exception as e:
        print(f'Error sending FCM notification: {e}')
        return False

