#nullable enable
using System;
using UnityEngine;

namespace IGP.UnitySDK
{
    /// <summary>The entry mode captured for this runtime launch, not current connection state.</summary>
    public enum IGPGameMode
    {
        Unknown = 0,
        Normal = 1,
        Multiplayer = 2,
    }

    public partial class IGPRuntimeManager
    {
        private bool launchContextCaptured;
        private IGPGameMode gameMode = IGPGameMode.Unknown;

        /// <summary>
        /// Captured once before Host and extension initialization. Leaving a room,
        /// reconnecting, or entering Multiplayer later does not change this value.
        /// Unknown means no supported, complete startup decision is available.
        /// </summary>
        public IGPGameMode GameMode => gameMode;

        internal void CaptureLaunchContext(string[] arguments, RuntimePlatform platform)
        {
            if (launchContextCaptured) return;
            pendingLaunchOptions = ParseCoreLaunchContext(arguments);
            runtimeInfo.CommitGameParams(pendingLaunchOptions?.gameParams ?? string.Empty);
            gameMode = ResolveLaunchGameMode(arguments, pendingLaunchOptions, platform);
            launchContextCaptured = true;
            // Never log arguments, game content, ticket, endpoint or bootstrap secret.
            LogSdkInfo("runtime", "launch-mode", $"event=captured mode={gameMode}");
            LogSdkInfo("runtime", "game-params", $"event=captured chars={runtimeInfo.GameParams.Length}");
        }

        private static IGPGameMode ResolveLaunchGameMode(
            string[] arguments, IGPCoreLaunchContext? launch, RuntimePlatform platform)
        {
            if (platform != RuntimePlatform.WindowsEditor && platform != RuntimePlatform.WindowsPlayer)
                return IGPGameMode.Unknown;
            if (launch?.HasHostedBootstrap == true) return IGPGameMode.Multiplayer;

            foreach (var argument in arguments)
            {
                if (IsLaunchOption(argument, "--arena-launch-ticket") ||
                    IsLaunchOption(argument, "--arena-bootstrap-endpoint") ||
                    IsLaunchOption(argument, "--arena-bootstrap-secret"))
                    return IGPGameMode.Unknown;
            }
            foreach (var argument in arguments)
                if (string.Equals(argument, "--worldsync-auto-connect=1", StringComparison.Ordinal))
                    return IGPGameMode.Multiplayer;
            return IGPGameMode.Normal;
        }

        private static bool IsLaunchOption(string argument, string option) =>
            string.Equals(argument, option, StringComparison.Ordinal) ||
            argument.StartsWith(option + "=", StringComparison.Ordinal);
    }
}
