using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;

/// <summary>
/// Covers the moving-chip rigidbody cache the PID gather loop reads, and runs the real physics
/// step to make sure the cheaper solver settings do not make chips teleport, tunnel or fly off.
/// </summary>
public class MovingChipPhysicsTests
{
    private GameObject chipPileGo;
    private PokerChipPile chipPile;
    private readonly List<GameObject> poolObjects = new List<GameObject>();
    private SimulationMode savedSimulationMode;

    [SetUp]
    public void SetUp()
    {
        // Physics.Simulate is ignored unless the project steps physics from script.
        savedSimulationMode = Physics.simulationMode;
        Physics.simulationMode = SimulationMode.Script;
        chipPileGo = new GameObject("MovingChipPile");
        chipPile = chipPileGo.AddComponent<PokerChipPile>();
        chipPile.denominationValues = new int[] { 5 };
    }

    [TearDown]
    public void TearDown()
    {
        Physics.simulationMode = savedSimulationMode;
        Object.DestroyImmediate(chipPileGo);
        foreach (var go in poolObjects) Object.DestroyImmediate(go);
        poolObjects.Clear();
    }

    private void BuildPile(int chips, bool withRigidbody = true)
    {
        var poolGo = new GameObject("Pool_5");
        poolObjects.Add(poolGo);
        var pool = poolGo.AddComponent<LocalObjectPool>();
        pool.denomination = 5;
        pool.Pool = new GameObject[chips];
        for (int c = 0; c < chips; c++)
        {
            var chip = new GameObject("Chip5_" + c);
            chip.transform.SetParent(poolGo.transform);
            if (withRigidbody)
            {
                Rigidbody rb = chip.AddComponent<Rigidbody>();
                rb.mass = 0.01f;
                rb.isKinematic = true;
                rb.useGravity = false;
            }
            // Thin disc footprint, flat once the chip is rotated to (-90, yaw, 0).
            BoxCollider box = chip.AddComponent<BoxCollider>();
            box.size = new Vector3(0.04f, 0.04f, 0.003f);
            box.enabled = false;
            pool.Pool[c] = chip;
        }
        VrcRuntimeFake.InvokeNoArg(pool, "Start");
        chipPile.denominationPools = new[] { pool };
        VrcRuntimeFake.InvokeNoArg(chipPile, "Start");
    }

    private Rigidbody[] Cache() { return (Rigidbody[])VrcRuntimeFake.GetPrivate(chipPile, "movingBodies"); }
    private GameObject[] Moving() { return (GameObject[])VrcRuntimeFake.GetPrivate(chipPile, "movingChips"); }
    private int MovingCount() { return (int)VrcRuntimeFake.GetPrivate(chipPile, "movingChipCount"); }

    private void FixedStep()
    {
        VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate");
        Physics.SyncTransforms();
        Physics.Simulate(Time.fixedDeltaTime);
    }

    // ---- cache ----

    [Test]
    public void Cache_MatchesEachMovingChipsRigidbody()
    {
        BuildPile(8);
        chipPile.SpawnDynamicChips(40, Vector3.zero);

        Assert.AreEqual(8, MovingCount());
        for (int i = 0; i < MovingCount(); i++)
        {
            Assert.IsNotNull(Cache()[i], "slot " + i);
            Assert.AreSame(Moving()[i].GetComponent<Rigidbody>(), Cache()[i], "slot " + i);
        }
    }

    [Test]
    public void Cache_HasNoDuplicatesWhenChipsAreAddedAgain()
    {
        BuildPile(6);
        chipPile.SpawnDynamicChips(15, Vector3.zero);
        int before = MovingCount();

        chipPile.MakeDisplayedChipsDynamic();

        Assert.AreEqual(before, MovingCount(), "Chips already moving must not be re-added");
        var seen = new HashSet<Rigidbody>();
        for (int i = 0; i < MovingCount(); i++) Assert.IsTrue(seen.Add(Cache()[i]), "duplicate body in slot " + i);
    }

    [Test]
    public void Cache_ClearedWhenTrackingEnds()
    {
        BuildPile(6);
        chipPile.SpawnDynamicChips(30, Vector3.zero);
        chipPile.StartAnimatedGather();

        chipPile.FinishAnimatedGather();

        Assert.AreEqual(0, MovingCount());
        foreach (Rigidbody body in Cache()) Assert.IsNull(body, "no stale body may stay cached");
    }

    [Test]
    public void Cache_SurvivesEndOfContractionBecauseChipsStayTracked()
    {
        BuildPile(6);
        chipPile.SpawnDynamicChips(30, Vector3.zero);
        chipPile.StartAnimatedGather();

        chipPile.EndAnimatedContraction();

        Assert.AreEqual(6, MovingCount());
        for (int i = 0; i < MovingCount(); i++) Assert.AreSame(Moving()[i].GetComponent<Rigidbody>(), Cache()[i]);
    }

    [Test]
    public void Cache_RebuiltForTheNextGatherWithoutStaleEntries()
    {
        BuildPile(4);
        chipPile.SpawnDynamicChips(10, Vector3.zero);
        chipPile.StartAnimatedGather();
        chipPile.FinishAnimatedGather();

        chipPile.SpawnDynamicChips(5, Vector3.zero);

        Assert.AreEqual(1, MovingCount());
        Assert.AreSame(Moving()[0].GetComponent<Rigidbody>(), Cache()[0]);
        for (int i = MovingCount(); i < Cache().Length; i++) Assert.IsNull(Cache()[i], "slot " + i);
    }

    [Test]
    public void Cache_ChipWithoutRigidbodyIsSkippedWithoutBreakingOthers()
    {
        BuildPile(3);
        chipPile.SpawnDynamicChips(15, new Vector3(0.3f, 0f, 0f));
        Object.DestroyImmediate(Moving()[1].GetComponent<Rigidbody>());
        // Stand-in for a chip that was never given a body: the cache still holds a destroyed ref.
        chipPile.StartAnimatedGather();

        Assert.DoesNotThrow(() => FixedStep());
        Assert.Greater(Cache()[0].velocity.sqrMagnitude, 0f, "the chips that still have bodies keep being driven");
        Assert.Greater(Cache()[2].velocity.sqrMagnitude, 0f, "the chips that still have bodies keep being driven");
    }

    [Test]
    public void Cache_PileWhoseChipsHaveNoRigidbodyAtAllDoesNotThrow()
    {
        BuildPile(3, withRigidbody: false);
        chipPile.SpawnDynamicChips(15, Vector3.zero);
        chipPile.StartAnimatedGather();

        Assert.AreEqual(3, MovingCount());
        foreach (Rigidbody body in Cache()) Assert.IsNull(body);
        Assert.DoesNotThrow(() => VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate"));
    }

    [Test]
    public void Cache_DestroyedChipMidGatherIsIgnored()
    {
        BuildPile(4);
        chipPile.SpawnDynamicChips(20, Vector3.zero);
        chipPile.StartAnimatedGather();
        Object.DestroyImmediate(Moving()[2]);

        Assert.DoesNotThrow(() => VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate"));
    }

    [Test]
    public void Cache_KinematicChipIsLeftAlone()
    {
        BuildPile(2);
        chipPile.SpawnDynamicChips(10, new Vector3(0.3f, 0f, 0f));
        chipPile.StartAnimatedGather();
        Rigidbody frozen = Cache()[0];
        frozen.isKinematic = true;
        Physics.SyncTransforms();
        Vector3 position = frozen.position;

        Assert.DoesNotThrow(() => FixedStep());

        Assert.AreEqual(position, frozen.position, "A kinematic chip must not be driven by the PID loop");
    }

    // ---- PID targets and rest threshold ----

    private Vector3[] TargetSlots() { return (Vector3[])VrcRuntimeFake.GetPrivate(chipPile, "gatherTargetLocal"); }

    private static Vector3 ExpectedSlot(int i, int count, float targetRadius)
    {
        float angle = i * 2.399963f;
        float radius = targetRadius * Mathf.Sqrt((i + 0.5f) / count);
        return new Vector3(Mathf.Cos(angle) * radius, 0f, Mathf.Sin(angle) * radius);
    }

    private void FreeFloat()
    {
        for (int i = 0; i < MovingCount(); i++) Cache()[i].useGravity = false;
    }

    [Test]
    public void Targets_FollowTheSpiralForTheCurrentChipCount()
    {
        BuildPile(7);
        chipPile.SpawnDynamicChips(35, Vector3.zero);
        chipPile.StartAnimatedGather();

        VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate");

        for (int i = 0; i < 7; i++)
        {
            Vector3 expected = ExpectedSlot(i, 7, chipPile.gatherPdTargetRadius);
            Assert.AreEqual(expected.x, TargetSlots()[i].x, 1e-5f, "slot " + i);
            Assert.AreEqual(expected.z, TargetSlots()[i].z, 1e-5f, "slot " + i);
            Assert.AreEqual(0f, TargetSlots()[i].y, 1e-6f);
        }
    }

    [Test]
    public void Targets_RebuiltWhenAChipJoinsMidGather()
    {
        BuildPile(6);
        chipPile.SpawnDynamicChips(15, Vector3.zero);
        chipPile.StartAnimatedGather();
        VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate");

        chipPile.SpawnDynamicChips(10, Vector3.zero);
        VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate");

        Assert.AreEqual(5, MovingCount());
        for (int i = 0; i < 5; i++)
            Assert.AreEqual(ExpectedSlot(i, 5, chipPile.gatherPdTargetRadius).x, TargetSlots()[i].x, 1e-5f, "slot " + i);
    }

    [Test]
    public void Targets_RebuiltForTheNextGatherWhenTheRadiusChanged()
    {
        BuildPile(3);
        chipPile.SpawnDynamicChips(15, Vector3.zero);
        chipPile.StartAnimatedGather();
        VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate");
        chipPile.EndAnimatedContraction();

        chipPile.gatherPdTargetRadius = 0.2f;
        chipPile.StartAnimatedGather();
        VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate");

        Assert.AreEqual(ExpectedSlot(2, 3, 0.2f).x, TargetSlots()[2].x, 1e-5f);
    }

    [Test]
    public void Pid_AcceleratesTowardTheSameTargetAsTheFormula()
    {
        BuildPile(1);
        chipPile.SpawnDynamicChips(5, new Vector3(0.3f, 0.1f, 0f));
        chipPile.StartAnimatedGather();
        FreeFloat();
        Rigidbody body = Cache()[0];
        body.drag = 0f;
        Physics.SyncTransforms();

        float dt = Time.fixedDeltaTime;
        Vector3 target = chipPileGo.transform.position + Vector3.up * chipPile.gatherPdHoverHeight
            + ExpectedSlot(0, 1, chipPile.gatherPdTargetRadius);
        Vector3 error = target - body.worldCenterOfMass;
        Vector3 integral = error * dt;
        Vector3 expected = error * chipPile.gatherPdSpring + integral * chipPile.gatherPidIntegral;
        if (expected.magnitude > chipPile.gatherPdMaxAcceleration) expected = expected.normalized * chipPile.gatherPdMaxAcceleration;

        FixedStep();

        Vector3 actual = body.velocity / dt;
        Assert.AreEqual(expected.x, actual.x, Mathf.Abs(expected.x) * 0.02f + 0.01f);
        Assert.AreEqual(expected.y, actual.y, Mathf.Abs(expected.y) * 0.02f + 0.01f);
        Assert.AreEqual(expected.z, actual.z, Mathf.Abs(expected.z) * 0.02f + 0.01f);
    }

    // ---- solver settings ----

    [Test]
    public void Settings_AppliedFromThePublicFields()
    {
        chipPile.movingChipSolverIterations = 5;
        chipPile.movingChipSolverVelocityIterations = 2;
        chipPile.movingChipMaxDepenetrationVelocity = 1.5f;
        BuildPile(2);

        chipPile.SpawnDynamicChips(10, Vector3.zero);

        foreach (Rigidbody body in Cache())
        {
            if (body == null) continue;
            Assert.AreEqual(5, body.solverIterations);
            Assert.AreEqual(2, body.solverVelocityIterations);
            Assert.AreEqual(1.5f, body.maxDepenetrationVelocity, 0.0001f);
            Assert.AreEqual(CollisionDetectionMode.ContinuousSpeculative, body.collisionDetectionMode);
        }
    }

    [Test]
    public void Settings_NonsenseValuesAreClamped()
    {
        chipPile.movingChipSolverIterations = 0;
        chipPile.movingChipSolverVelocityIterations = -3;
        chipPile.movingChipMaxDepenetrationVelocity = -1f;
        BuildPile(1);

        chipPile.SpawnDynamicChips(5, Vector3.zero);

        Rigidbody body = Cache()[0];
        Assert.GreaterOrEqual(body.solverIterations, 1);
        Assert.GreaterOrEqual(body.solverVelocityIterations, 1);
        Assert.Greater(body.maxDepenetrationVelocity, 0f);
    }

    // ---- real physics: no teleporting or weird motion ----

    [Test]
    public void FixedUpdate_OnlyAppliesForces_NeverWritesPositions()
    {
        BuildPile(4);
        chipPile.SpawnDynamicChips(20, new Vector3(0.4f, 0f, 0f));
        chipPile.StartAnimatedGather();
        Physics.SyncTransforms();
        var before = new Vector3[MovingCount()];
        for (int i = 0; i < before.Length; i++) before[i] = Cache()[i].position;

        VrcRuntimeFake.InvokeNoArg(chipPile, "FixedUpdate");

        for (int i = 0; i < before.Length; i++)
            Assert.AreEqual(before[i], Cache()[i].position, "chip " + i + " moved without a physics step");
    }

    [Test]
    public void FixedUpdate_PullsAFarChipTowardThePile()
    {
        BuildPile(1);
        chipPile.SpawnDynamicChips(5, new Vector3(0.4f, 0f, 0f));
        chipPile.StartAnimatedGather();
        Rigidbody body = Cache()[0];
        Physics.SyncTransforms();
        float before = Vector3.Distance(new Vector3(body.position.x, 0f, body.position.z), Vector3.zero);

        for (int i = 0; i < 20; i++) FixedStep();

        float after = Vector3.Distance(new Vector3(body.position.x, 0f, body.position.z), Vector3.zero);
        Assert.Less(after, before, "The gather should draw the chip in");
    }

    [TestCase(3, 1, 2f, TestName = "Gather_NewSolverDefaults_ChipsStaySane")]
    [TestCase(6, 1, 10f, TestName = "Gather_LegacySolverSettings_ChipsStaySane")]
    public void Gather_ChipsMoveSmoothlyAndStayOnTheTable(int iterations, int velocityIterations, float depenetration)
    {
        chipPile.movingChipSolverIterations = iterations;
        chipPile.movingChipSolverVelocityIterations = velocityIterations;
        chipPile.movingChipMaxDepenetrationVelocity = depenetration;
        chipPile.gatherTransportDuration = 100f; // stay in the transport phase for the whole run

        GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Cube);
        poolObjects.Add(floor);
        floor.transform.position = new Vector3(0f, -0.05f, 0f);
        floor.transform.localScale = new Vector3(4f, 0.1f, 4f);

        BuildPile(40);
        // Four pools' worth of chips spawned around the pile, as a big pot transfer would.
        chipPile.SpawnDynamicChips(200, new Vector3(0.05f, 0.1f, 0f));
        chipPile.StartAnimatedGather();
        Physics.SyncTransforms();

        int count = MovingCount();
        Assert.AreEqual(40, count);
        var last = new Vector3[count];
        for (int i = 0; i < count; i++) last[i] = Cache()[i].position;

        float maxStep = 0f;
        float maxSpeed = 0f;
        int steps = Mathf.RoundToInt(1.5f / Time.fixedDeltaTime);
        for (int s = 0; s < steps; s++)
        {
            FixedStep();
            for (int i = 0; i < count; i++)
            {
                Rigidbody body = Cache()[i];
                Vector3 p = body.position;
                Assert.IsFalse(float.IsNaN(p.x) || float.IsNaN(p.y) || float.IsNaN(p.z), "chip " + i + " went NaN");
                maxStep = Mathf.Max(maxStep, Vector3.Distance(p, last[i]));
                maxSpeed = Mathf.Max(maxSpeed, body.velocity.magnitude);
                last[i] = p;
                Assert.Greater(p.y, -0.03f, "chip " + i + " tunnelled through the table at step " + s);
                Assert.Less(p.y, 0.6f, "chip " + i + " was launched upward at step " + s);
            }
        }

        Assert.Greater(maxSpeed, 0.01f, "the physics step never moved anything, so this test proved nothing");
        Assert.Less(maxStep, 0.06f, "a chip jumped " + maxStep + "m in one physics step");
        Assert.Less(maxSpeed, 5f, "a chip reached " + maxSpeed + "m/s");
        for (int i = 0; i < count; i++)
        {
            Vector3 p = Cache()[i].position;
            Assert.Less(new Vector2(p.x, p.z).magnitude, 0.25f, "chip " + i + " drifted away from the pile");
            Assert.IsFalse(Cache()[i].isKinematic, "chip " + i + " froze mid-gather");
        }
    }
}
