using System.Collections.Generic;
using System.Reflection;
using NUnit.Framework;
using UdonSharp;

// Pins what any client can invoke over the network on our behaviours, so new entry points get reviewed.
public class NetworkSurfaceTests
{
    // Plain names are legacy events, [NC] marks [NetworkCallable]. Each must be read-only, cosmetic,
    // guarded by NetworkCalling.InNetworkCall, or validate NetworkCalling.CallingPlayer.
    private static readonly Dictionary<string, string[]> Reviewed = new Dictionary<string, string[]>
    {
        { "AudioPoolPlayer", new[] { "Play" } },
        { "CharityCard", new[] { "GetCurrentTarget", "IsBeingHeld" } },
        { "GrabbableHand", new[] { "IsFolded" } },
        { "HoldemGame", new[] {
            "[NC]ReportHoleCards", "[NC]RequestHoleCards", "CollectRoundPilesToPot", "GetTimeMillis", "IsShowdown" } },
        { "HoldemPlayer", new[] {
            "[NC]ReceiveHoleCards", "ActivePlayerId", "CanHandlePhysicalChips", "CanStartPhysicalRaise", "CanUsePhysicalBetting", "GetPhysicalCallAmount", "GetPhysicalMinimumRaiseBet", "GetPhysicalSourceBaselineValue", "GetPhysicalStackValue", "IsSeated", "IsShownBySeatedPlayer", "OwnerName", "OwnerPlayerBalanceComponent" } },
        { "HoldemAuthority", new[] { "[NC]RequestCharity" } },
        { "PlayerBalanceComponent", new[] {
            "[NC]RequestBigWinAmount", "[NC]RequestBigWinCards", "[NC]RequestModifyBalance", "[NC]RequestRecordHandClass", "[NC]RequestRecordHoldemHandStats", "[NC]RequestRecordProfit", "[NC]RequestRecordStat",
            "GetBalance", "GetCBetOpportunities", "GetCBetPercent", "GetCBets", "GetDonation", "GetDonationsReceived", "GetFoldToCBetOpportunities", "GetFoldToCBetPercent",
            "GetFoldToThreeBetOpportunities", "GetFoldToThreeBetPercent", "GetFolds", "GetFoldsToCBet", "GetFoldsToThreeBet", "GetHandsPlayed", "GetHatsGiven", "GetHatsReceived",
            "GetBiggestWin", "GetBiggestWinHand", "GetLosses", "GetPFRPercent", "GetPfrHands", "GetProfit", "GetThreeBetOpportunities", "GetThreeBetPercent", "GetThreeBets", "GetTrackedHands",
            "GetVPIPPercent", "GetVpipHands", "GetWins", "IsReady" } },
        { "PokerChipPile", new[] { "AnimatedGatherDuration", "EndAnimatedContraction", "FinishAnimatedGather", "GetTotalDisplayedValue", "MakeDisplayedChipsDynamic", "OpenContainer", "ReleaseAllToPools", "StartAnimatedGather", "UpdateText" } },
        { "SFXPlayer", new[] { "Play", "PlayParticles" } },
        { "TransformMoverUdon", new[] { "IsMoving", "ResetToInitial", "Stop" } },
        { "VRCButton", new[] { "PlayAnimation", "PlayParticles" } },
        { "WheelWelfareComponent", new[] {
            "[NC]NotifyPlayerSpin", "[NC]RequestSpin", "CheckWelfareCooldownExpired", "GetCooldownDuration",
            "GetWelfareStatus", "HasReceivedPlayerData", "OnBalanceChanged" } },
        { "HatBell", new[] { "GetRemainingCooldown", "IsOnCooldown", "PlayBellEffects" } },
        { "HatGremlifier", new[] { "ReapplySizeCap" } },
        { "HatItem", new[] { "GetCurrentTarget", "IsBeingHeld", "PlaySuccessParticles", "PlaySuccessSound" } },
        { "HatManager", new[] {
            "[NC]MasterApplyHat", "[NC]MasterRemoveHat", "[NC]OnHatEvent", "[NC]RestoreOwnHat", "GetCostToPlace",
            "GetCostToRemove", "GetRewardToTarget", "IsPersistenceRestoreComplete", "RefreshHats" } },
        { "HatPlayerData", new[] { "IsReady" } },
    };

    private static readonly string[] Assemblies = { "HoldemAssembly", "UdonChipsHat" };

    private static readonly HashSet<string> UnityMessages = new HashSet<string>
    {
        "Awake", "Start", "Update", "LateUpdate", "FixedUpdate", "PostLateUpdate",
        "OnEnable", "OnDisable", "OnDestroy", "OnValidate", "Reset"
    };

    [Test]
    public void OnlyReviewedMethodsAreNetworkCallable()
    {
        var unreviewed = new List<string>();
        var stale = new List<string>();
        var seen = new HashSet<string>();

        foreach (var type in NetworkedBehaviours())
        {
            seen.Add(type.Name);
            var reachable = Reachable(type);
            string[] reviewedNames;
            var reviewed = new HashSet<string>(Reviewed.TryGetValue(type.Name, out reviewedNames) ? reviewedNames : new string[0]);

            foreach (var name in reachable)
            {
                if (!reviewed.Contains(name)) unreviewed.Add(type.Name + "." + name);
            }
            foreach (var name in reviewed)
            {
                if (!reachable.Contains(name)) stale.Add(type.Name + "." + name);
            }
        }
        foreach (var typeName in Reviewed.Keys)
        {
            if (!seen.Contains(typeName)) stale.Add(typeName + " (not a networked behaviour)");
        }

        Assert.IsEmpty(unreviewed, "Network-callable but not reviewed:\n  " + string.Join("\n  ", unreviewed));
        Assert.IsEmpty(stale, "Reviewed but no longer network-callable:\n  " + string.Join("\n  ", stale));
    }

    private static IEnumerable<System.Type> NetworkedBehaviours()
    {
        foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
        {
            if (System.Array.IndexOf(Assemblies, assembly.GetName().Name) < 0) continue;
            foreach (var type in assembly.GetTypes())
            {
                if (type.IsAbstract || !typeof(UdonSharpBehaviour).IsAssignableFrom(type)) continue;
                if (SecurityTests.IsNetworked(type)) yield return type;
            }
        }
    }

    private static HashSet<string> Reachable(System.Type type)
    {
        var names = new HashSet<string>();
        foreach (var method in type.GetMethods(BindingFlags.Instance | BindingFlags.Public))
        {
            if (method.IsSpecialName || method.DeclaringType == typeof(UdonSharpBehaviour)) continue;
            if (!typeof(UdonSharpBehaviour).IsAssignableFrom(method.DeclaringType)) continue;
            if (method.GetBaseDefinition().DeclaringType == typeof(UdonSharpBehaviour)) continue;
            if (UnityMessages.Contains(method.Name)) continue;

            bool networkCallable = false;
            foreach (var attribute in method.GetCustomAttributes(true))
            {
                if (attribute.GetType().Name == "NetworkCallableAttribute") networkCallable = true;
            }

            if (networkCallable) names.Add("[NC]" + method.Name);
            else if (method.GetParameters().Length == 0 && !method.Name.StartsWith("_")) names.Add(method.Name);
        }
        return names;
    }
}
