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

"""macOS application activation helper.

GTK4 on macOS needs explicit NSApplication activation to show windows properly.
"""

def activate_macos_app():
    """Activate the macOS application so windows appear.

    This configures NSApplication to behave as a regular GUI app and
    brings it to the foreground.
    """
    try:
        from AppKit import (
            NSApplication,
            NSApplicationActivationPolicyRegular,
            NSApplicationActivateAllWindows,
            NSApplicationActivateIgnoringOtherApps,
        )

        # Get the shared NSApplication instance
        app = NSApplication.sharedApplication()

        # Set activation policy to regular app (shows in Dock, can be focused)
        # This must be done before activating
        app.setActivationPolicy_(NSApplicationActivationPolicyRegular)

        # Activate the app and bring it to the foreground
        # activateIgnoringOtherApps: brings app to front regardless of other apps
        app.activateIgnoringOtherApps_(True)

        import logging
        log = logging.getLogger(__name__)
        log.info("macOS app activated successfully")

        return True
    except ImportError:
        # PyObjC not available
        import logging
        log = logging.getLogger(__name__)
        log.warning("PyObjC AppKit not available - window may not activate automatically")
        return False
    except Exception as e:
        import logging
        log = logging.getLogger(__name__)
        log.warning(f"Failed to activate macOS app: {e}")
        import traceback
        traceback.print_exc()
        return False
