using System.Runtime.InteropServices;
using UnityEngine;

/// <summary>
/// C# wrapper for the native SparklePlugin on macOS.
/// Provides auto-update functionality via the Sparkle framework.
/// On non-macOS platforms, all methods are no-ops.
/// </summary>
public static class SparkleUpdater {
#if UNITY_STANDALONE_OSX && !UNITY_EDITOR
    private const string PluginName = "SparklePlugin";

    [DllImport(PluginName)]
    private static extern void SparklePlugin_Initialize();

    [DllImport(PluginName)]
    private static extern void SparklePlugin_CheckForUpdates();

    [DllImport(PluginName)]
    private static extern void SparklePlugin_CheckForUpdatesInBackground();

    [DllImport(PluginName)]
    private static extern int SparklePlugin_IsCheckingForUpdates();

    [DllImport(PluginName)]
    private static extern int SparklePlugin_GetAutomaticallyChecksForUpdates();

    [DllImport(PluginName)]
    private static extern void SparklePlugin_SetAutomaticallyChecksForUpdates(int enabled);

    [DllImport(PluginName)]
    private static extern int SparklePlugin_IsRunningFromReadOnlyVolume();

    [DllImport(PluginName)]
    private static extern void SparklePlugin_ShowDMGWarning();

    private static bool _initialized = false;

    /// <summary>
    /// Initialize the Sparkle updater. Should be called once at app startup.
    /// This starts automatic background update checks based on Info.plist settings.
    /// </summary>
    public static void Initialize() {
        if (_initialized) {
            Debug.Log("SparkleUpdater: Already initialized");
            return;
        }

        Debug.Log("SparkleUpdater: Initializing Sparkle");
        try {
            SparklePlugin_Initialize();
            _initialized = true;
            Debug.Log("SparkleUpdater: Initialization complete");
        } catch (System.Exception e) {
            Debug.LogError($"SparkleUpdater: Failed to initialize: {e.Message}");
        }
    }

    /// <summary>
    /// Manually check for updates. Shows the update UI to the user.
    /// </summary>
    public static void CheckForUpdates() {
        if (!_initialized) {
            Debug.LogWarning("SparkleUpdater: Not initialized");
            return;
        }
        SparklePlugin_CheckForUpdates();
    }

    /// <summary>
    /// Check for updates silently in the background.
    /// Only shows UI if an update is found.
    /// </summary>
    public static void CheckForUpdatesInBackground() {
        if (!_initialized) {
            Debug.LogWarning("SparkleUpdater: Not initialized");
            return;
        }
        SparklePlugin_CheckForUpdatesInBackground();
    }

    /// <summary>
    /// Returns true if an update check is currently in progress.
    /// </summary>
    public static bool IsCheckingForUpdates {
        get {
            if (!_initialized) return false;
            return SparklePlugin_IsCheckingForUpdates() != 0;
        }
    }

    /// <summary>
    /// Gets or sets whether automatic update checks are enabled.
    /// </summary>
    public static bool AutomaticallyChecksForUpdates {
        get {
            if (!_initialized) return false;
            return SparklePlugin_GetAutomaticallyChecksForUpdates() != 0;
        }
        set {
            if (!_initialized) return;
            SparklePlugin_SetAutomaticallyChecksForUpdates(value? 1: 0);
        }
    }

    /// <summary>
    /// Check if app is running from a read-only volume (e.g., mounted DMG).
    /// </summary>
    public static bool IsRunningFromReadOnlyVolume() {
        return SparklePlugin_IsRunningFromReadOnlyVolume() != 0;
    }

    /// <summary>
    /// Show a warning that app is running from DMG and needs to be installed.
    /// This will quit the app after the user dismisses the dialog.
    /// </summary>
    public static void ShowDMGWarning() { SparklePlugin_ShowDMGWarning(); }

#else
    // Stub implementations for non-macOS platforms and Editor

    public static void Initialize() { Debug.Log("SparkleUpdater: Not available on this platform"); }

    public static void CheckForUpdates() {
        Debug.Log("SparkleUpdater: Not available on this platform");
    }

    public static void CheckForUpdatesInBackground() {
        Debug.Log("SparkleUpdater: Not available on this platform");
    }

    public static bool IsCheckingForUpdates => false;

    public static bool AutomaticallyChecksForUpdates {
        get => false;
        set {}
    }

    public static bool IsRunningFromReadOnlyVolume() { return false; }

    public static void ShowDMGWarning() {}
#endif
}
