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

"""Login Items integration for macOS autostart."""

import logging

log = logging.getLogger(__name__)

try:
    from Foundation import NSURL
    from ServiceManagement import (
        SMAppService,
    )
    SERVICEMANAGEMENT_AVAILABLE = True
except ImportError:
    log.warning("ServiceManagement framework not available")
    SERVICEMANAGEMENT_AVAILABLE = False


def set_autostart_macos(enabled: bool) -> bool:
    """Enable or disable autostart on macOS using Login Items.

    Args:
        enabled: True to enable autostart, False to disable

    Returns:
        True if successful, False otherwise

    Note: This requires macOS 13+ for SMAppService API.
    For older macOS versions, consider using LSSharedFileList (deprecated).
    """
    if not SERVICEMANAGEMENT_AVAILABLE:
        log.warning("ServiceManagement not available - autostart not supported")
        return False

    try:
        # Get the main app service
        service = SMAppService.mainAppService()

        if enabled:
            # Register the app to launch at login
            error = service.registerAndReturnError_(None)
            if error[1]:
                log.error(f"Failed to enable autostart: {error[1]}")
                return False
            log.info("Autostart enabled successfully")
            return True
        else:
            # Unregister from login items
            error = service.unregisterAndReturnError_(None)
            if error[1]:
                log.error(f"Failed to disable autostart: {error[1]}")
                return False
            log.info("Autostart disabled successfully")
            return True

    except Exception as e:
        log.error(f"Failed to set autostart: {e}")
        return False


def is_autostart_enabled_macos() -> bool:
    """Check if autostart is currently enabled on macOS.

    Returns:
        True if autostart is enabled, False otherwise
    """
    if not SERVICEMANAGEMENT_AVAILABLE:
        return False

    try:
        service = SMAppService.mainAppService()
        status = service.status()

        # SMAppService status values:
        # 0 = notRegistered
        # 1 = enabled
        # 2 = requiresApproval
        # 3 = notFound

        return status == 1  # enabled

    except Exception as e:
        log.error(f"Failed to check autostart status: {e}")
        return False
