using Steamworks;
using System;
using UnityEngine;
using Debug = UnityEngine.Debug;

namespace NeoriginPCSDK
{
    /// <summary>
    /// Steam SDK管理器
    /// 单例模式，管理Steam SDK的生命周期和核心功能
    /// </summary>
    public class SteamManager : MonoBehaviour
    {
        private static SteamManager _instance;
        public static SteamManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    var go = new GameObject("SteamManager");
                    _instance = go.AddComponent<SteamManager>();
                    DontDestroyOnLoad(go);
                }
                return _instance;
            }
        }

        /// <summary>
        /// Steam是否已初始化
        /// </summary>
        public bool IsInitialized { get; private set; } = false;

        /// <summary>
        /// 是否检查了所有权
        /// </summary>
        public bool IsOwnershipChecked { get; private set; } = false;

        /// <summary>
        /// 用户是否拥有游戏
        /// </summary>
        public bool IsOwned { get; private set; } = false;

        // Auth Ticket回调
        private Callback<GetTicketForWebApiResponse_t> _getTicketCallback;
        private Action<string> _ticketSuccessCallback;
        private Action<string> _ticketFailCallback;

        // Steam支付授权回调
        private Callback<MicroTxnAuthorizationResponse_t> _microTxnCallback;
        private Action<bool, string> _payAuthCallback;

        // 初始化状态
        private bool _isInitializing = false;

        /// <summary>
        /// 初始化Steam SDK
        /// </summary>
        /// <param name="appId">Steam AppID，默认使用480(测试AppID)</param>
        /// <returns>初始化是否成功</returns>
        public bool InitSteam(uint appId = 480)
        {
            if (IsInitialized)
            {
                Debug.Log("<color=yellow>Steam已经初始化过了</color>");
                return true;
            }

            if (_isInitializing)
            {
                Debug.Log("<color=yellow>Steam正在初始化中...</color>");
                return false;
            }

            _isInitializing = true;

            try
            {
                System.Environment.SetEnvironmentVariable("SteamAppId", appId.ToString());
                System.Environment.SetEnvironmentVariable("SteamGameId", appId.ToString());
                // 检查是否需要通过Steam启动
                // 如果不是通过Steam启动，RestartAppIfNecessary会尝试启动Steam客户端
                if (SteamAPI.RestartAppIfNecessary((AppId_t)appId))
                {
                    Debug.Log("<color=yellow>游戏需要通过Steam启动，正在启动Steam客户端...</color>");
                    Application.Quit();
                    return false;
                }

                // 初始化Steam API
                if (!SteamAPI.Init())
                {
                    Debug.LogError("<color=red>Steam API初始化失败！请确保Steam客户端正在运行。</color>");
                    _isInitializing = false;
                    return false;
                }

                // 获取SteamID
                CSteamID steamId = SteamUser.GetSteamID();
                if (steamId == CSteamID.Nil)
                {
                    Debug.LogError("<color=red>无法获取SteamID，请确保用户已登录Steam。</color>");
                    SteamAPI.Shutdown();
                    _isInitializing = false;
                    return false;
                }

                // 初始化成功，缓存数据
                SteamData.Instance.SteamId = steamId.m_SteamID.ToString();
                SteamData.Instance.AppId = appId;
                SteamData.Instance.PersonaName = SteamFriends.GetPersonaName();
                SteamData.Instance.GameLanguage = SteamApps.GetCurrentGameLanguage();
                SteamData.Instance.IsInitialized = true;

                // 注册Auth Ticket回调
                _getTicketCallback = Callback<GetTicketForWebApiResponse_t>.Create(OnGetTicketResponse);

                // 注册Steam支付授权回调
                _microTxnCallback = Callback<MicroTxnAuthorizationResponse_t>.Create(OnMicroTxnAuthorizationResponse);

                IsInitialized = true;
                _isInitializing = false;

                Debug.Log($"<color=green>Steam初始化成功！</color>\n" +
                          $"SteamID: {SteamData.Instance.SteamId}\n" +
                          $"用户名: {SteamData.Instance.PersonaName}\n" +
                          $"AppID: {SteamUtils.GetAppID().m_AppId}\n" +
                          $"语言: {SteamData.Instance.GameLanguage}");

                return true;
            }
            catch (Exception e)
            {
                Debug.LogError($"<color=red>Steam初始化异常: {e.Message}</color>");
                _isInitializing = false;
                return false;
            }
        }
        

        /// <summary>
        /// 获取用于Web API验证的Auth Ticket
        /// </summary>
        /// <param name="onSuccess">成功回调，返回Ticket的十六进制字符串</param>
        /// <param name="onFail">失败回调，返回错误消息</param>
        /// <param name="identity">用于验证的身份标识，默认为"neorigin"</param>
        public void GetAuthTicket(Action<string> onSuccess, Action<string> onFail, string identity = "neorigin")
        {
            if (!IsInitialized)
            {
                Debug.LogError("<color=red>Steam未初始化，无法获取Auth Ticket</color>");
                onFail?.Invoke("Steam not initialized");
                return;
            }

            _ticketSuccessCallback = onSuccess;
            _ticketFailCallback = onFail;

            try
            {
                // 请求用于Web API验证的Auth Ticket
                HAuthTicket hTicket = SteamUser.GetAuthTicketForWebApi(null);
                if (hTicket == HAuthTicket.Invalid)
                {
                    Debug.LogError("<color=red>获取Auth Ticket失败：返回无效票据</color>");
                    onFail?.Invoke("Failed to get auth ticket");
                    return;
                }
                Debug.Log("<color=cyan>正在请求Steam Auth Ticket...</color>");
            }
            catch (Exception e)
            {
                Debug.LogError($"<color=red>请求Auth Ticket异常: {e.Message}</color>");
                onFail?.Invoke(e.Message);
            }
        }

        /// <summary>
        /// Auth Ticket响应回调
        /// </summary>
        private void OnGetTicketResponse(GetTicketForWebApiResponse_t pCallback)
        {
            if (pCallback.m_eResult == EResult.k_EResultOK)
            {
                try
                {
                    // 将Ticket数据转换为十六进制字符串
                    int ticketSize = (int)pCallback.m_cubTicket;
                    byte[] ticketData = new byte[ticketSize];

                    // m_rgubTicket 是 byte[] 类型，直接复制
                    for (int i = 0; i < ticketSize && i < pCallback.m_rgubTicket.Length; i++)
                    {
                        ticketData[i] = pCallback.m_rgubTicket[i];
                    }

                    string ticketHex = BitConverter.ToString(ticketData, 0, ticketSize).Replace("-", "").ToLower();

                    Debug.Log($"<color=green>获取Auth Ticket成功，长度: {ticketHex.Length}</color>");
                    Debug.Log("SDK当前识别到的 AppID: " + SteamUtils.GetAppID().m_AppId);
                    _ticketSuccessCallback?.Invoke(ticketHex);
                }
                catch (Exception e)
                {
                    Debug.LogError($"<color=red>处理Auth Ticket异常: {e.Message}</color>");
                    _ticketFailCallback?.Invoke(e.Message);
                }
            }
            else
            {
                string errorMsg = $"Steam返回错误: {pCallback.m_eResult} ({(int)pCallback.m_eResult})";
                Debug.LogError($"<color=red>获取Auth Ticket失败: {errorMsg}</color>");
                _ticketFailCallback?.Invoke(errorMsg);
            }

            // 清理回调
            _ticketSuccessCallback = null;
            _ticketFailCallback = null;
        }

        /// <summary>
        /// 注册Steam支付授权回调
        /// 当用户在Steam Overlay中确认或取消支付时触发
        /// </summary>
        public void RegisterPayAuthCallback(Action<bool, string> callback)
        {
            _payAuthCallback = callback;
        }

        /// <summary>
        /// 清除Steam支付授权回调
        /// </summary>
        public void ClearPayAuthCallback()
        {
            _payAuthCallback = null;
        }

        /// <summary>
        /// Steam支付授权响应回调
        /// 当用户在Steam Overlay中完成支付操作后触发
        /// </summary>
        private void OnMicroTxnAuthorizationResponse(MicroTxnAuthorizationResponse_t pCallback)
        {
            uint appId = (uint)pCallback.m_unAppID;
            ulong orderId = (ulong)pCallback.m_ulOrderID;
            byte authorized = pCallback.m_bAuthorized;

            Debug.Log($"<color=cyan>收到Steam支付授权回调: AppID={appId}, OrderID={orderId}, Authorized={authorized}</color>");

            // 验证AppID是否匹配
            if (appId != SteamData.Instance.AppId)
            {
                Debug.LogWarning($"<color=yellow>Steam支付回调AppID不匹配: {appId} != {SteamData.Instance.AppId}</color>");
                return;
            }

            // 调用注册的回调
            bool isAuthorized = authorized != 0;
            string orderIdStr = orderId.ToString();
            _payAuthCallback?.Invoke(isAuthorized, orderIdStr);
        }

        /// <summary>
        /// 每帧更新，调用Steam回调
        /// </summary>
        void Update()
        {
            if (IsInitialized)
            {
                SteamAPI.RunCallbacks();
            }
        }

        /// <summary>
        /// 销毁时清理Steam
        /// </summary>
        void OnDestroy()
        {
            if (IsInitialized)
            {
                Debug.Log("<color=cyan>正在关闭Steam API...</color>");
                SteamAPI.Shutdown();
                IsInitialized = false;
                SteamData.Instance.Clear();

                // 清理回调
                if (_getTicketCallback != null)
                {
                    _getTicketCallback.Dispose();
                    _getTicketCallback = null;
                }

                if (_microTxnCallback != null)
                {
                    _microTxnCallback.Dispose();
                    _microTxnCallback = null;
                }
            }

            if (_instance == this)
            {
                _instance = null;
            }
        }

        /// <summary>
        /// 打开Steam好友列表
        /// </summary>
        public void OpenFriendsList()
        {
            if (IsInitialized)
            {
                SteamFriends.ActivateGameOverlay("friends");
            }
        }

        /// <summary>
        /// 打开Steam用户资料
        /// </summary>
        /// <param name="steamId">目标用户SteamID</param>
        public void OpenUserProfile(string steamId)
        {
            if (IsInitialized && ulong.TryParse(steamId, out ulong id))
            {
                SteamFriends.ActivateGameOverlayToUser("steamid", new CSteamID(id));
            }
        }

        /// <summary>
        /// 打开Steam商店页面
        /// </summary>
        /// <param name="appId">AppID</param>
        public void OpenStorePage(uint appId)
        {
            if (IsInitialized)
            {
                SteamFriends.ActivateGameOverlayToStore((AppId_t)appId, EOverlayToStoreFlag.k_EOverlayToStoreFlag_None);
            }
        }

        /// <summary>
        /// 使用Steam叠加界面内置浏览器打开网页
        /// 用户会自动登录Steam，无需二次登录
        /// </summary>
        /// <param name="url">要打开的URL</param>
        public void OpenSteamOverlayWebPage(string url)
        {
            if (IsInitialized)
            {
                Debug.Log($"<color=cyan>使用Steam Overlay打开网页: {url}</color>");
                SteamFriends.ActivateGameOverlayToWebPage(url);
            }
            else
            {
                Debug.LogWarning("<color=yellow>Steam未初始化，使用系统浏览器打开</color>");
                Application.OpenURL(url);
            }
        }
    }
}
