import json
import logging
import os

from .models import Notification

logger = logging.getLogger(__name__)


def send_push_notification(user, title, body, target_url=""):
    """
    Dispatch a Web Push message to all of a user's registered subscriptions.
    Fails silently — never raises or propagates exceptions.
    """
    try:
        from .models import PushSubscription
        subscriptions = list(PushSubscription.objects.filter(user=user))
    except Exception:
        return

    if not subscriptions:
        return

    private_key = os.environ.get("VAPID_PRIVATE_KEY", "")
    email = os.environ.get("VAPID_EMAIL", "mailto:support@chithie.com")

    if not private_key:
        return

    payload = json.dumps({
        "title": title,
        "body": body,
        "url": target_url or "/",
    })

    for sub in subscriptions:
        try:
            from pywebpush import webpush, WebPushException
            webpush(
                subscription_info={
                    "endpoint": sub.endpoint,
                    "keys": {"p256dh": sub.p256dh, "auth": sub.auth},
                },
                data=payload,
                vapid_private_key=private_key,
                vapid_claims={"sub": email},
            )
        except Exception as exc:
            # Log at debug level only — push failure must NEVER surface to the user
            logger.debug("Push dispatch failed for subscription %s: %s", sub.id, exc)
            # If it's a 410 Gone the subscription is expired; remove it
            try:
                from pywebpush import WebPushException
                if isinstance(exc, WebPushException) and exc.response is not None:
                    if exc.response.status_code in (404, 410):
                        sub.delete()
            except Exception:
                pass


def create_notification(user, notification_type, title, body="", target_url=""):
    """
    Creates an in-app notification record for the specified user and
    dispatches a Web Push to all of their registered devices.
    Fails safely without breaking user requests.
    """
    try:
        notif = Notification.objects.create(
            user=user,
            notification_type=notification_type,
            title=title,
            body=body[:500],
            target_url=target_url[:255],
        )
    except Exception:
        return None

    # Fire-and-forget push dispatch (silent on failure)
    send_push_notification(user, title, body[:100], target_url)
    return notif
