# Copyright 2026, Jiri Eischmann <jiri@eischmann.cz> and the meshy contributors
# SPDX-License-Identifier: GPL-3.0-or-later

"""Native macOS notification service using UserNotifications framework.

IMPORTANT: This implementation requires proper code signing with an Apple
Developer ID certificate. Ad-hoc signed builds will fail with:
"Notifications are not allowed for this application" (UNErrorDomain Code=1)

For development/unsigned builds, use GioNotificationService instead.
This will work once the app is properly signed and notarized for distribution.
"""

import logging

try:
    from Foundation import NSBundle
    from objc import nil
    import UserNotifications as UN

    OBJC_AVAILABLE = True
except ImportError:
    OBJC_AVAILABLE = False

from ..notification_base import NotificationService

log = logging.getLogger(__name__)


class MacOSNotificationService(NotificationService):
    """Native macOS notification service using UNUserNotificationCenter.

    Uses the modern UserNotifications framework (macOS 10.14+) which properly
    integrates with macOS Notification Center, respecting user preferences
    and Focus modes.

    **IMPORTANT:** Requires proper code signing with Developer ID.
    Will fail with "Notifications are not allowed" on unsigned builds.
    """

    def __init__(self, application):
        """Initialize macOS notification service.

        Args:
            application: GTK application instance (unused but kept for interface compatibility)
        """
        self._app = application
        self._center = None
        self._authorized = False

        if not OBJC_AVAILABLE:
            log.warning("PyObjC UserNotifications not available - notifications disabled")
            return

        try:
            # Get the shared notification center
            self._center = UN.UNUserNotificationCenter.currentNotificationCenter()

            # Request authorization for notifications
            self._request_authorization()

            log.info("MacOSNotificationService initialized")
        except Exception as e:
            log.error(f"Failed to initialize notification center: {e}")
            self._center = None

    def _request_authorization(self):
        """Request notification authorization from the user.

        Note: Will fail with UNErrorDomain Code=1 on unsigned builds.
        """
        if not self._center:
            return

        def completion_handler(granted, error):
            if error:
                log.error(f"Notification authorization error: {error}")
                log.error(
                    "This usually means the app is not properly signed with a "
                    "Developer ID certificate. Notifications require signed builds."
                )
                self._authorized = False
            else:
                self._authorized = granted
                if granted:
                    log.info("Notification authorization granted")
                else:
                    log.warning("Notification authorization denied by user")

        # Request authorization for alerts, sounds, and badges
        options = (
            UN.UNAuthorizationOptionAlert
            | UN.UNAuthorizationOptionSound
            | UN.UNAuthorizationOptionBadge
        )

        self._center.requestAuthorizationWithOptions_completionHandler_(
            options, completion_handler
        )

    def send_notification(self, title: str, body: str, notification_id: str) -> None:
        """Send a native macOS notification.

        Args:
            title: Notification title
            body: Notification body text
            notification_id: Unique identifier for this notification
        """
        if not self.is_supported():
            log.debug("Notifications not supported, skipping")
            return

        try:
            # Create notification content
            content = UN.UNMutableNotificationContent.alloc().init()
            content.setTitle_(title)
            content.setBody_(body)
            content.setSound_(UN.UNNotificationSound.defaultSound())

            # Set bundle identifier for proper app attribution
            bundle_id = NSBundle.mainBundle().bundleIdentifier()
            if not bundle_id:
                bundle_id = "page.codeberg.sesivany.Meshy"

            # Create a trigger (deliver immediately)
            trigger = nil  # nil trigger = deliver immediately

            # Create the request
            request = UN.UNNotificationRequest.requestWithIdentifier_content_trigger_(
                notification_id, content, trigger
            )

            # Add the request to the notification center
            def completion_handler(error):
                if error:
                    log.error(f"Failed to send notification: {error}")
                else:
                    log.debug(f"Sent notification: {title}")

            self._center.addNotificationRequest_withCompletionHandler_(
                request, completion_handler
            )

        except Exception as e:
            log.error(f"Exception sending notification: {e}")

    def is_supported(self) -> bool:
        """Check if macOS notifications are supported.

        Returns:
            True if PyObjC is available and notification center is initialized
        """
        return OBJC_AVAILABLE and self._center is not None
