using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using VRC.SDKBase;

/// <summary>
/// Minimal in-memory stand-in for the VRChat runtime, for EditMode tests.
///
/// The SDK exposes its runtime as public static delegate fields (Networking._LocalPlayer,
/// Networking._IsOwner, PlayerData._setInt, VRCPlayerApi._GetPlayerId, ...). Swapping those
/// lets EditMode tests drive the real production code paths - including persistence writes -
/// instead of only testing pure helper methods.
///
/// These are process-global statics: every Install() MUST be paired with Uninstall() in
/// [TearDown], or the fakes leak into other tests.
///
/// PlayerData lives in VRCSDK3, which the EditorTests assembly does not reference directly,
/// so it is reached by reflection.
/// </summary>
public class VrcRuntimeFake
{
    private const BindingFlags StaticFlags = BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public;
    private const BindingFlags InstFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;

    /// <summary>Fake persistence store, keyed exactly as PlayerData keys it.</summary>
    public readonly Dictionary<string, object> Store = new Dictionary<string, object>();

    /// <summary>Ordered log of every PlayerData write, e.g. "SetInt(UdonChipsHat/HasHat, 0)".</summary>
    public readonly List<string> Writes = new List<string>();

    /// <summary>Local player seen by Networking.LocalPlayer.</summary>
    public VRCPlayerApi LocalPlayer { get; private set; }

    /// <summary>What Networking.IsOwner returns when IsOwnerOf is not set. Defaults to true.</summary>
    public bool IsOwnerResult = true;

    /// <summary>
    /// Per-object ownership, for tests that need to own one object but not another
    /// (e.g. we own our player object, but the master owns the HatManager).
    /// Null falls back to IsOwnerResult.
    /// </summary>
    public Func<GameObject, bool> IsOwnerOf;

    private static Type PlayerDataType
    {
        get
        {
            foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                var t = asm.GetType("VRC.SDK3.Persistence.PlayerData");
                if (t != null) return t;
            }
            throw new InvalidOperationException("VRC.SDK3.Persistence.PlayerData not found");
        }
    }

    private readonly Dictionary<string, object> originals = new Dictionary<string, object>();
    private bool installed;

    private static FieldInfo NetField(string n) { return typeof(Networking).GetField(n, StaticFlags); }
    private static FieldInfo PlayerField(string n) { return typeof(VRCPlayerApi).GetField(n, StaticFlags); }
    private static FieldInfo DataField(string n) { return PlayerDataType.GetField(n, StaticFlags); }

    private void Save(string key, FieldInfo f) { originals[key] = f.GetValue(null); }

    /// <summary>Builds a usable VRCPlayerApi without a running VRChat client.</summary>
    public static VRCPlayerApi MakePlayer(int playerId, string displayName, bool isLocal)
    {
        var p = new VRCPlayerApi();
        typeof(VRCPlayerApi).GetField("isLocal", InstFlags).SetValue(p, isLocal);
        typeof(VRCPlayerApi).GetField("displayName", InstFlags).SetValue(p, displayName);
        typeof(VRCPlayerApi).GetField("mPlayerId", InstFlags).SetValue(p, playerId);
        typeof(VRCPlayerApi).GetField("_isValid", InstFlags).SetValue(p, true);
        return p;
    }

    /// <summary>Registers a player so VRCPlayerApi.GetPlayers / GetPlayerById can see it.</summary>
    public void AddPlayer(VRCPlayerApi player)
    {
        var list = (List<VRCPlayerApi>)PlayerField("sPlayers").GetValue(null);
        if (!list.Contains(player)) list.Add(player);
    }

    public void Install(int localPlayerId = 5, string localName = "Bob")
    {
        if (installed) throw new InvalidOperationException("VrcRuntimeFake already installed");
        installed = true;

        Save("_GetPlayerId", PlayerField("_GetPlayerId"));
        Save("_GetPlayerById", PlayerField("_GetPlayerById"));
        Save("sPlayers", PlayerField("sPlayers"));
        Save("_LocalPlayer", NetField("_LocalPlayer"));
        Save("_IsOwner", NetField("_IsOwner"));
        foreach (var n in new[] { "_setInt", "_setString", "_hasKey", "_getInt", "_getString" })
            Save(n, DataField(n));

        PlayerField("_GetPlayerId").SetValue(null, (Func<VRCPlayerApi, int>)(
            pl => (int)typeof(VRCPlayerApi).GetField("mPlayerId", InstFlags).GetValue(pl)));

        PlayerField("sPlayers").SetValue(null, new List<VRCPlayerApi>());

        PlayerField("_GetPlayerById").SetValue(null, (Func<int, VRCPlayerApi>)(id =>
        {
            var list = (List<VRCPlayerApi>)PlayerField("sPlayers").GetValue(null);
            foreach (var pl in list) if (pl.playerId == id) return pl;
            return null;
        }));

        LocalPlayer = MakePlayer(localPlayerId, localName, true);
        AddPlayer(LocalPlayer);

        NetField("_LocalPlayer").SetValue(null, (Func<VRCPlayerApi>)(() => LocalPlayer));
        NetField("_IsOwner").SetValue(null, (Func<VRCPlayerApi, GameObject, bool>)(
            (a, go) => IsOwnerOf != null ? IsOwnerOf(go) : IsOwnerResult));

        DataField("_setInt").SetValue(null, (Action<string, int>)((k, v) =>
        { Store[k] = v; Writes.Add($"SetInt({k}, {v})"); }));
        DataField("_setString").SetValue(null, (Action<string, string>)((k, v) =>
        { Store[k] = v; Writes.Add($"SetString({k}, \"{v}\")"); }));
        DataField("_hasKey").SetValue(null, (Func<VRCPlayerApi, string, bool>)((pl, k) => Store.ContainsKey(k)));
        DataField("_getInt").SetValue(null, (Func<VRCPlayerApi, string, int>)((pl, k) =>
            Store.ContainsKey(k) ? (int)Store[k] : 0));
        DataField("_getString").SetValue(null, (Func<VRCPlayerApi, string, string>)((pl, k) =>
            Store.ContainsKey(k) ? (string)Store[k] : ""));
    }

    public void Uninstall()
    {
        if (!installed) return;
        installed = false;
        PlayerField("_GetPlayerId").SetValue(null, originals["_GetPlayerId"]);
        PlayerField("_GetPlayerById").SetValue(null, originals["_GetPlayerById"]);
        PlayerField("sPlayers").SetValue(null, originals["sPlayers"]);
        NetField("_LocalPlayer").SetValue(null, originals["_LocalPlayer"]);
        NetField("_IsOwner").SetValue(null, originals["_IsOwner"]);
        foreach (var n in new[] { "_setInt", "_setString", "_hasKey", "_getInt", "_getString" })
            DataField(n).SetValue(null, originals[n]);
        originals.Clear();
    }

    // ---- convenience ----

    public void SeedInt(string key, int value) { Store[key] = value; }
    public void SeedString(string key, string value) { Store[key] = value; }
    public int GetInt(string key) { return Store.ContainsKey(key) ? (int)Store[key] : -1; }
    public void ClearWrites() { Writes.Clear(); }
    public string WriteLog() { return string.Join("\n  ", Writes); }

    /// <summary>Invokes a private/parameterless method, resolving the exact overload.</summary>
    public static void InvokeNoArg(object target, string method)
    {
        var m = target.GetType().GetMethod(method, InstFlags, null, Type.EmptyTypes, null);
        if (m == null) throw new MissingMethodException(target.GetType().Name + "." + method);
        m.Invoke(target, null);
    }

    public static object GetPrivate(object target, string field)
    {
        var f = target.GetType().GetField(field, InstFlags);
        if (f == null) throw new MissingFieldException(target.GetType().Name + "." + field);
        return f.GetValue(target);
    }

    public static void SetPrivate(object target, string field, object value)
    {
        var f = target.GetType().GetField(field, InstFlags);
        if (f == null) throw new MissingFieldException(target.GetType().Name + "." + field);
        f.SetValue(target, value);
    }
}
