"""
Service de Push Notifications avec Firebase Cloud Messaging (FCM)
"""
import json
import requests
from typing import List, Optional, Dict, Any
from datetime import datetime
import logging

logger = logging.getLogger(__name__)

class PushNotificationService:
    """Service pour envoyer des push notifications via FCM"""
    
    def __init__(self, fcm_server_key: Optional[str] = None):
        """
        Initialiser le service de push notifications
        
        Args:
            fcm_server_key: Clé serveur Firebase Cloud Messaging
        """
        self.fcm_server_key = fcm_server_key or "YOUR_FCM_SERVER_KEY"
        self.fcm_url = "https://fcm.googleapis.com/fcm/send"
        
    def send_push_notification(
        self,
        device_tokens: List[str],
        title: str,
        body: str,
        data: Optional[Dict[str, Any]] = None,
        priority: str = "high",
        sound: str = "default"
    ) -> Dict[str, Any]:
        """
        Envoyer une push notification à un ou plusieurs appareils
        
        Args:
            device_tokens: Liste des tokens FCM des appareils
            title: Titre de la notification
            body: Corps de la notification
            data: Données supplémentaires (optionnel)
            priority: Priorité (high, normal)
            sound: Son de la notification
            
        Returns:
            Résultat de l'envoi
        """
        if not device_tokens:
            logger.warning("Aucun token d'appareil fourni")
            return {"success": False, "error": "No device tokens"}
        
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"key={self.fcm_server_key}"
        }
        
        # Préparer le payload
        payload = {
            "registration_ids": device_tokens,
            "priority": priority,
            "notification": {
                "title": title,
                "body": body,
                "sound": sound,
                "click_action": "FLUTTER_NOTIFICATION_CLICK",
                "badge": "1"
            }
        }
        
        # Ajouter les données personnalisées si fournies
        if data:
            payload["data"] = data
        
        try:
            response = requests.post(
                self.fcm_url,
                headers=headers,
                data=json.dumps(payload),
                timeout=10
            )
            
            if response.status_code == 200:
                result = response.json()
                logger.info(f"✅ Push notification envoyée: {result}")
                return {
                    "success": True,
                    "result": result,
                    "success_count": result.get("success", 0),
                    "failure_count": result.get("failure", 0)
                }
            else:
                logger.error(f"❌ Erreur FCM: {response.status_code} - {response.text}")
                return {
                    "success": False,
                    "error": f"FCM error: {response.status_code}",
                    "details": response.text
                }
                
        except Exception as e:
            logger.error(f"❌ Exception lors de l'envoi push: {str(e)}")
            return {
                "success": False,
                "error": str(e)
            }
    
    def send_session_expired_notification(self, device_tokens: List[str]) -> Dict[str, Any]:
        """
        Envoyer une notification d'expiration de session
        
        Args:
            device_tokens: Liste des tokens FCM
            
        Returns:
            Résultat de l'envoi
        """
        return self.send_push_notification(
            device_tokens=device_tokens,
            title="🔒 Session Expirée",
            body="Votre session a expiré. Veuillez vous reconnecter.",
            data={
                "type": "session_expired",
                "action": "redirect_to_login",
                "timestamp": datetime.now().isoformat()
            },
            priority="high"
        )
    
    def send_transaction_notification(
        self,
        device_tokens: List[str],
        transaction_type: str,
        amount: float,
        status: str
    ) -> Dict[str, Any]:
        """
        Envoyer une notification de transaction
        
        Args:
            device_tokens: Liste des tokens FCM
            transaction_type: Type de transaction
            amount: Montant
            status: Statut de la transaction
            
        Returns:
            Résultat de l'envoi
        """
        emoji_map = {
            "completed": "✅",
            "pending": "⏳",
            "failed": "❌"
        }
        emoji = emoji_map.get(status.lower(), "📱")
        
        return self.send_push_notification(
            device_tokens=device_tokens,
            title=f"{emoji} Transaction {status}",
            body=f"{transaction_type}: {amount:,.0f} FCFA",
            data={
                "type": "transaction",
                "transaction_type": transaction_type,
                "amount": amount,
                "status": status,
                "timestamp": datetime.now().isoformat()
            }
        )
    
    def send_loan_notification(
        self,
        device_tokens: List[str],
        loan_status: str,
        amount: float,
        due_date: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Envoyer une notification de prêt
        
        Args:
            device_tokens: Liste des tokens FCM
            loan_status: Statut du prêt (approved, rejected, due_soon)
            amount: Montant du prêt
            due_date: Date d'échéance (optionnel)
            
        Returns:
            Résultat de l'envoi
        """
        if loan_status == "approved":
            title = "✅ Prêt Approuvé"
            body = f"Votre prêt de {amount:,.0f} FCFA a été approuvé !"
        elif loan_status == "rejected":
            title = "❌ Prêt Refusé"
            body = f"Votre demande de prêt de {amount:,.0f} FCFA a été refusée."
        elif loan_status == "due_soon":
            title = "⏰ Échéance de Prêt"
            body = f"Votre prêt de {amount:,.0f} FCFA arrive à échéance le {due_date}"
        else:
            title = "📋 Notification de Prêt"
            body = f"Prêt de {amount:,.0f} FCFA - {loan_status}"
        
        return self.send_push_notification(
            device_tokens=device_tokens,
            title=title,
            body=body,
            data={
                "type": "loan",
                "loan_status": loan_status,
                "amount": amount,
                "due_date": due_date,
                "timestamp": datetime.now().isoformat()
            }
        )
    
    def send_nfc_payment_notification(
        self,
        device_tokens: List[str],
        merchant_name: str,
        amount: float,
        location: Optional[str] = None
    ) -> Dict[str, Any]:
        """
        Envoyer une notification de paiement NFC
        
        Args:
            device_tokens: Liste des tokens FCM
            merchant_name: Nom du commerçant
            amount: Montant payé
            location: Localisation (optionnel)
            
        Returns:
            Résultat de l'envoi
        """
        location_text = f" à {location}" if location else ""
        
        return self.send_push_notification(
            device_tokens=device_tokens,
            title="💳 Paiement NFC Effectué",
            body=f"{amount:,.0f} FCFA payé chez {merchant_name}{location_text}",
            data={
                "type": "nfc_payment",
                "merchant_name": merchant_name,
                "amount": amount,
                "location": location,
                "timestamp": datetime.now().isoformat()
            }
        )
    
    def send_low_balance_notification(
        self,
        device_tokens: List[str],
        current_balance: float,
        threshold: float = 1000
    ) -> Dict[str, Any]:
        """
        Envoyer une notification de solde faible
        
        Args:
            device_tokens: Liste des tokens FCM
            current_balance: Solde actuel
            threshold: Seuil d'alerte
            
        Returns:
            Résultat de l'envoi
        """
        return self.send_push_notification(
            device_tokens=device_tokens,
            title="⚠️ Solde Faible",
            body=f"Votre solde est de {current_balance:,.0f} FCFA. Pensez à recharger votre compte.",
            data={
                "type": "low_balance",
                "current_balance": current_balance,
                "threshold": threshold,
                "timestamp": datetime.now().isoformat()
            },
            priority="high"
        )
    
    def send_account_verification_notification(
        self,
        device_tokens: List[str],
        verification_status: str
    ) -> Dict[str, Any]:
        """
        Envoyer une notification de vérification de compte
        
        Args:
            device_tokens: Liste des tokens FCM
            verification_status: Statut de vérification (verified, rejected)
            
        Returns:
            Résultat de l'envoi
        """
        if verification_status == "verified":
            title = "✅ Compte Vérifié"
            body = "Félicitations ! Votre compte TIM CASH a été vérifié."
        else:
            title = "❌ Vérification Échouée"
            body = "La vérification de votre compte a échoué. Veuillez réessayer."
        
        return self.send_push_notification(
            device_tokens=device_tokens,
            title=title,
            body=body,
            data={
                "type": "account_verification",
                "status": verification_status,
                "timestamp": datetime.now().isoformat()
            }
        )


# Instance globale du service
push_service = PushNotificationService()
