using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using RebootKit.Engine.Main;
using Steamworks;
using Logger = RebootKit.Engine.Foundation.Logger;

namespace RebootKit.Engine.Steam {
    static class SteamManager {
        static readonly Logger s_Logger = new Logger(nameof(SteamManager));
        
        public static bool IsInitialized { get; private set; } = false;
        
        internal static async UniTask InitializeAsync(CancellationToken cancellationToken = default) {
            s_Logger.Info("Initializing Steam Manager...");
            IsInitialized = false;

            try {
                SteamClient.Init(RR.EngineConfig.steamAppID, true);
            } catch (Exception ex) {
                s_Logger.Error($"Failed to initialize Steam Client: {ex.Message}");
                return;
            }
            
            IsInitialized = true;
            
            await UniTask.Yield(cancellationToken);

            SteamFriends.OnGameRichPresenceJoinRequested += OnJoinRequested;
        }
        
        internal static void Shutdown() {
            if (!IsInitialized) {
                s_Logger.Error("Steam Manager is not initialized. Skipping operation.");
                return;
            }
            
            s_Logger.Info("Shutting down Steam Manager...");
            
            SteamFriends.OnGameRichPresenceJoinRequested -= OnJoinRequested;
            SteamClient.Shutdown();

            IsInitialized = false;
        }
        
        static void OnJoinRequested(Friend friend, string key) {
            s_Logger.Info($"Join request received from {friend.Name} with key: {key}");
            
            if (string.IsNullOrEmpty(key)) {
                s_Logger.Warning("Join request key is empty. Cannot process join request.");
                return;
            }

            if (ulong.TryParse(key, out ulong steamID)) {
                RR.ConnectWithSteamID(steamID);
            }
        }
    }
}