"""
FCM Push Notification Service for NOMAZRA.
Uses Firebase Admin SDK with the kelthos-nomazra project.
This is SEPARATE from kelthos-platform's Firebase config.
"""
import os
import json
import logging

import firebase_admin
from firebase_admin import credentials, messaging

logger = logging.getLogger(__name__)

# Separate Firebase app instance for NOMAZRA
_nomazra_app = None


def _get_app():
    """Initialize or return the NOMAZRA Firebase app."""
    global _nomazra_app
    if _nomazra_app is not None:
        return _nomazra_app

    cred_path = os.getenv('NOMAZRA_FIREBASE_CREDENTIALS')
    if not cred_path:
        raise ValueError("NOMAZRA_FIREBASE_CREDENTIALS env var not set")

    if not os.path.isfile(cred_path):
        raise FileNotFoundError(f"Firebase credentials file not found: {cred_path}")

    cred = credentials.Certificate(cred_path)
    _nomazra_app = firebase_admin.initialize_app(
        cred, name='nomazra-fcm'
    )
    return _nomazra_app


def send_notification(fcm_token, title, body, data=None):
    """
    Send a push notification to a single device.

    Args:
        fcm_token: Device FCM registration token
        title: Notification title
        body: Notification body text
        data: Optional dict of string key-value pairs for data message
    """
    if not fcm_token:
        logger.warning("No FCM token provided, skipping notification")
        return None

    try:
        app = _get_app()

        notification = messaging.Notification(
            title=title,
            body=body,
        )

        android_config = messaging.AndroidConfig(
            priority='high',
            notification=messaging.AndroidNotification(
                channel_id='nomazra_default',
                icon='ic_notification',
                color='#1B4DFF',
            ),
        )

        message = messaging.Message(
            notification=notification,
            android=android_config,
            token=fcm_token,
            data={k: str(v) for k, v in (data or {}).items()},
        )

        response = messaging.send(message, app=app)
        logger.info("FCM sent: %s", response)
        return response
    except messaging.UnregisteredError:
        logger.warning("FCM token unregistered: %s...", fcm_token[:20])
        return None
    except Exception as e:
        logger.error("FCM send failed: %s", e)
        return None


def send_to_multiple(fcm_tokens, title, body, data=None):
    """Send notification to multiple devices."""
    if not fcm_tokens:
        return []

    app = _get_app()

    notification = messaging.Notification(title=title, body=body)
    clean_data = {k: str(v) for k, v in (data or {}).items()}

    message = messaging.MulticastMessage(
        notification=notification,
        tokens=fcm_tokens,
        data=clean_data,
        android=messaging.AndroidConfig(
            priority='high',
            notification=messaging.AndroidNotification(
                channel_id='nomazra_default',
                icon='ic_notification',
                color='#1B4DFF',
            ),
        ),
    )

    response = messaging.send_each_for_multicast(message, app=app)
    logger.info(
        "FCM multicast: %d success, %d failure",
        response.success_count, response.failure_count,
    )
    return response


# ── Notification helpers for NOMAZRA features ──

def notify_reminder(fcm_token, reminder_title, reminder_body):
    """Send a reminder notification."""
    return send_notification(
        fcm_token, 
        f"⏰ Reminder: {reminder_title}",
        reminder_body,
        data={'type': 'reminder'},
    )


def notify_document_ready(fcm_token, document_name):
    """Notify user their document analysis is complete."""
    return send_notification(
        fcm_token,
        "Document Analysis Complete",
        f"Your analysis of '{document_name}' is ready.",
        data={'type': 'document_ready', 'document_name': document_name},
    )


def notify_chat_response(fcm_token, conversation_id):
    """Notify user of new AI response (for background processing)."""
    return send_notification(
        fcm_token,
        "NOMAZRA",
        "Your legal consultation response is ready.",
        data={'type': 'chat_response', 'conversation_id': str(conversation_id)},
    )
