import os
from typing import Optional, Dict, List, Callable

from flask import current_app

try:
    import firebase_admin
    from firebase_admin import credentials, messaging
except Exception:
    firebase_admin = None
    credentials = None
    messaging = None

_firebase_app = None


def init_firebase():
    global _firebase_app

    if _firebase_app:
        return _firebase_app

    # firebase library not installed
    if firebase_admin is None or credentials is None:
        current_app.logger.warning("Firebase library not available; skipping push notifications")
        return None

    path = (
        current_app.config.get("FIREBASE_SERVICE_ACCOUNT_JSON")
        or os.environ.get("FIREBASE_SERVICE_ACCOUNT_JSON")
    )

    # firebase config not set
    if not path:
        current_app.logger.warning("FIREBASE_SERVICE_ACCOUNT_JSON not set; skipping push notifications")
        return None

    # file path invalid
    if not os.path.exists(path):
        current_app.logger.warning("Firebase service account file not found at %s; skipping push notifications", path)
        return None

    try:
        # reuse existing firebase app if already initialized
        existing_apps = getattr(firebase_admin, "_apps", None)
        if existing_apps:
            _firebase_app = firebase_admin.get_app()
            return _firebase_app
    except Exception:
        pass

    try:
        cred = credentials.Certificate(path)
        _firebase_app = firebase_admin.initialize_app(cred)
        return _firebase_app
    except Exception:
        current_app.logger.exception("Failed to initialize Firebase; skipping push notifications")
        return None


def send_push(
    tokens: List[str],
    title: str,
    body: str,
    data: Optional[Dict[str, str]] = None,
    on_invalid_tokens: Optional[Callable[[List[str]], None]] = None,
):
    """
    Multicast push via FCM.
    Safe behavior:
    - if firebase is not configured, do not crash
    - return zero counts
    """
    tokens = [t for t in (tokens or []) if t]
    if not tokens:
        return {"sent": 0, "failed": 0, "invalid": 0, "skipped": True}

    app = init_firebase()
    if app is None or messaging is None:
        return {"sent": 0, "failed": 0, "invalid": 0, "skipped": True}

    try:
        data = {k: str(v) for k, v in (data or {}).items()}

        msg = messaging.MulticastMessage(
            notification=messaging.Notification(title=title, body=body),
            data=data,
            tokens=tokens,
        )

        resp = messaging.send_each_for_multicast(msg)

        invalid_tokens: List[str] = []

        for i, r in enumerate(resp.responses):
            if r.success:
                continue

            tok = tokens[i]
            err = r.exception
            code = ""
            try:
                code = getattr(err, "code", "") or ""
            except Exception:
                code = ""

            msg_txt = str(err or "").lower()

            if (
                "registration-token-not-registered" in msg_txt
                or "not registered" in msg_txt
                or "unregistered" in msg_txt
                or "invalid-argument" in msg_txt
                or code in ("UNREGISTERED", "INVALID_ARGUMENT")
            ):
                invalid_tokens.append(tok)

        if invalid_tokens and on_invalid_tokens:
            try:
                on_invalid_tokens(invalid_tokens)
            except Exception:
                current_app.logger.exception("Failed to deactivate invalid tokens")

        return {
            "sent": resp.success_count,
            "failed": resp.failure_count,
            "invalid": len(invalid_tokens),
            "skipped": False,
        }

    except Exception:
        current_app.logger.exception("Push notification failed")
        return {"sent": 0, "failed": len(tokens), "invalid": 0, "skipped": True}