using System;
using System.Threading.Tasks;
using UnityEngine;

namespace CoolGameX
{
    /// <summary>
    /// Main entry point for the Cool GameX platform SDK.
    ///
    /// Typical usage (in your game's Start):
    /// <code>
    /// await CoolAPI.Initialize("your-game-slug", "https://your-server.com");
    /// await CoolAPI.Auth.LoginWithToken(savedToken);
    /// await CoolAPI.Achievements.Unlock("speed_runner");
    /// CoolAPI.Playtime.StartSession();
    /// // ... on quit:
    /// CoolAPI.Playtime.EndSession();
    /// </code>
    /// </summary>
    public static class CoolAPI
    {
        /// <summary>The game's slug, as registered on Cool GameX.</summary>
        public static string GameSlug { get; private set; }

        /// <summary>Base URL of the Cool GameX backend, e.g. https://api.coolgamex.com</summary>
        public static string ServerUrl { get; private set; }

        /// <summary>The current player's Supabase JWT, if logged in.</summary>
        public static string Token { get; internal set; }

        public static bool IsInitialized { get; private set; }

        /// <summary>True once a player token is present (logged in).</summary>
        public static bool IsAuthenticated => !string.IsNullOrEmpty(Token);

        /// <summary>
        /// True if the SDK has successfully reached the Cool GameX server
        /// (updated automatically after every request; also see CheckConnection).
        /// </summary>
        public static bool IsConnected { get; internal set; }

        /// <summary>Details of the most recent failed request (status + message).</summary>
        public static string LastError { get; internal set; }

        /// <summary>HTTP status code of the most recent request.</summary>
        public static long LastStatus { get; internal set; }

        public static Auth Auth { get; private set; }
        public static Achievements Achievements { get; private set; }
        public static Playtime Playtime { get; private set; }
        public static DLC DLC { get; private set; }
        public static Stats Stats { get; private set; }

        /// <summary>
        /// Initialize the SDK. Reads the launcher token from the
        /// <c>--cgx-token=JWT</c> launch argument automatically.
        /// </summary>
        public static Task Initialize(string gameSlug, string serverUrl)
        {
            if (string.IsNullOrEmpty(gameSlug))
                throw new ArgumentException("gameSlug is required", nameof(gameSlug));
            if (string.IsNullOrEmpty(serverUrl))
                throw new ArgumentException("serverUrl is required", nameof(serverUrl));

            GameSlug = gameSlug;
            ServerUrl = serverUrl.TrimEnd('/');

            Auth = new Auth();
            Achievements = new Achievements();
            Playtime = new Playtime();
            DLC = new DLC();
            Stats = new Stats();

            // Pick up the JWT the launcher passed on the command line.
            var launcherToken = ReadLaunchToken();
            if (!string.IsNullOrEmpty(launcherToken))
            {
                Token = launcherToken;
                Debug.Log("[CoolAPI] Authenticated from launcher token.");
            }

            IsInitialized = true;
            Debug.Log($"[CoolAPI] Initialized for '{gameSlug}' → {ServerUrl}");
            return Task.CompletedTask;
        }

        /// <summary>
        /// Reads the JWT from the <c>--cgx-token=JWT</c> launch argument.
        /// Returns null when launched outside of the Cool GameX launcher.
        /// </summary>
        public static string ReadLaunchToken()
        {
            const string prefix = "--cgx-token=";
            foreach (var arg in Environment.GetCommandLineArgs())
            {
                if (arg.StartsWith(prefix, StringComparison.Ordinal))
                    return arg.Substring(prefix.Length);
            }
            return null;
        }

        /// <summary>
        /// Pings the Cool GameX server and updates <see cref="IsConnected"/>.
        /// Useful for showing an online/offline indicator in your game.
        /// </summary>
        public static async Task<bool> CheckConnection()
        {
            var res = await Net.Get("/api/health", auth: false);
            IsConnected = res.Success;
            return IsConnected;
        }

        /// <summary>
        /// One-line status string, handy for debugging:
        /// "initialized=true connected=true authenticated=false".
        /// </summary>
        public static string StatusLine() =>
            $"initialized={IsInitialized} connected={IsConnected} authenticated={IsAuthenticated}";

        internal static void EnsureReady()
        {
            if (!IsInitialized)
                throw new InvalidOperationException(
                    "CoolAPI.Initialize must be called before using the SDK.");
        }
    }
}
