#if UNITY_ANDROID && DAVANCI_GPGS && !UNITY_EDITOR
using System;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using GooglePlayGames.BasicApi.SavedGame;
using UnityEngine;

namespace Davanci.Nexus
{
    // Android cloud slot via Play Games Saved Games (DAVANCI_GPGS, device builds only).
    public sealed class NexusGpgsProvider : INexusCloudProvider
    {
        readonly string _snapshotName;

        public NexusGpgsProvider(string snapshotName)
            => _snapshotName = string.IsNullOrEmpty(snapshotName) ? "nexus_save" : snapshotName;

        public bool Available =>
            PlayGamesPlatform.Instance != null && PlayGamesPlatform.Instance.IsAuthenticated();

        public void Push(byte[] data, Action<bool> onDone)
        {
            if (!Available) { onDone?.Invoke(false); return; }
            OpenSnapshot((ok, meta) =>
            {
                if (!ok || meta == null) { onDone?.Invoke(false); return; }
                try
                {
                    var update = new SavedGameMetadataUpdate.Builder().Build();
                    PlayGamesPlatform.Instance.SavedGame.CommitUpdate(
                        meta, update, data ?? Array.Empty<byte>(),
                        (status, _) => onDone?.Invoke(status == SavedGameRequestStatus.Success));
                }
                catch (Exception e)
                {
                    Debug.LogWarning($"[Nexus] GPGS commit failed: {e.Message}");
                    onDone?.Invoke(false);
                }
            });
        }

        public void Pull(Action<bool, byte[]> onDone)
        {
            if (!Available) { onDone?.Invoke(false, null); return; }
            OpenSnapshot((ok, meta) =>
            {
                if (!ok || meta == null) { onDone?.Invoke(false, null); return; }
                try
                {
                    PlayGamesPlatform.Instance.SavedGame.ReadBinaryData(meta, (status, bytes) =>
                    {
                        bool read = status == SavedGameRequestStatus.Success;
                        onDone?.Invoke(read, read && bytes != null && bytes.Length > 0 ? bytes : null);
                    });
                }
                catch (Exception e)
                {
                    Debug.LogWarning($"[Nexus] GPGS read failed: {e.Message}");
                    onDone?.Invoke(false, null);
                }
            });
        }

        void OpenSnapshot(Action<bool, ISavedGameMetadata> onOpen)
        {
            try
            {
                PlayGamesPlatform.Instance.SavedGame.OpenWithAutomaticConflictResolution(
                    _snapshotName,
                    DataSource.ReadCacheOrNetwork,
                    ConflictResolutionStrategy.UseMostRecentlySaved,
                    (status, meta) => onOpen?.Invoke(status == SavedGameRequestStatus.Success, meta));
            }
            catch (Exception e)
            {
                Debug.LogWarning($"[Nexus] GPGS open snapshot failed: {e.Message}");
                onOpen?.Invoke(false, null);
            }
        }
    }
}
#endif
