"""
Firebase Cloud Messaging (FCM) service for sending push notifications
"""
import os
import json
from typing import Optional, Dict, Any
from firebase_admin import credentials, messaging, initialize_app
from firebase_admin.exceptions import FirebaseError
import logging

logger = logging.getLogger(__name__)

# Initialize Firebase Admin SDK
try:
    # Try to get FCM credentials from environment variable (JSON string or file path)
    fcm_credentials = os.getenv("FCM_CREDENTIALS")
    if fcm_credentials:
        # If it's a file path
        if os.path.isfile(fcm_credentials):
            cred = credentials.Certificate(fcm_credentials)
        else:
            # If it's a JSON string
            cred = credentials.Certificate(json.loads(fcm_credentials))
        initialize_app(cred)
        logger.info("FCM initialized successfully")
    else:
        logger.warning("FCM_CREDENTIALS not found. Push notifications will not work.")
except Exception as e:
    logger.error(f"Failed to initialize FCM: {str(e)}")


class FCMService:
    """Service for sending FCM push notifications"""
    
    @staticmethod
    async def send_notification(
        device_token: str,
        title: str,
        body: str,
        data: Optional[Dict[str, Any]] = None,
        image_url: Optional[str] = None
    ) -> bool:
        """
        Send a push notification to a single device
        
        Args:
            device_token: FCM device token
            title: Notification title
            body: Notification body
            data: Optional data payload (dict)
            image_url: Optional image URL for notification
            
        Returns:
            bool: True if sent successfully, False otherwise
        """
        if not device_token:
            logger.warning("Device token is empty, skipping notification")
            return False
        
        try:
            # Build notification message
            notification = messaging.Notification(
                title=title,
                body=body,
                image=image_url
            )
            
            # Build message
            message = messaging.Message(
                notification=notification,
                data=data or {},
                token=device_token,
                android=messaging.AndroidConfig(
                    priority="high",
                    notification=messaging.AndroidNotification(
                        sound="default",
                        priority="high"
                    )
                ),
                apns=messaging.APNSConfig(
                    payload=messaging.APNSPayload(
                        aps=messaging.Aps(
                            sound="default",
                            badge=1
                        )
                    )
                )
            )
            
            # Send message
            response = messaging.send(message)
            logger.info(f"Successfully sent notification to {device_token[:20]}... Response: {response}")
            return True
            
        except messaging.UnregisteredError:
            logger.warning(f"Device token is unregistered: {device_token[:20]}...")
            return False
        except messaging.InvalidArgumentError as e:
            logger.error(f"Invalid argument for FCM: {str(e)}")
            return False
        except FirebaseError as e:
            logger.error(f"Firebase error sending notification: {str(e)}")
            return False
        except Exception as e:
            logger.error(f"Unexpected error sending notification: {str(e)}")
            return False
    
    @staticmethod
    async def send_multiple_notifications(
        notifications: list[Dict[str, Any]]
    ) -> Dict[str, bool]:
        """
        Send multiple notifications
        
        Args:
            notifications: List of dicts with keys: device_token, title, body, data, image_url
            
        Returns:
            Dict mapping device_token to success status
        """
        results = {}
        for notif in notifications:
            device_token = notif.get("device_token")
            if device_token:
                success = await FCMService.send_notification(
                    device_token=device_token,
                    title=notif.get("title", ""),
                    body=notif.get("body", ""),
                    data=notif.get("data"),
                    image_url=notif.get("image_url")
                )
                results[device_token] = success
        return results


# Singleton instance
fcm_service = FCMService()
