using NUnit.Framework;
using UnityEditor;
using UnityEngine;

// The hole-card highlight must hug the VISIBLE card, and the peek rig must be laid over it.
//
// The card quads are padded around the printed card (and the front/back masks are offset from each other), so mesh
// bounds prove nothing. Everything here is measured from the texture's alpha mask, the same test the shaders clip with
// (CardSilhouette), in the card's local space, at the prefab's rest pose.
//
//  - The 3x5 bone grid spans exactly the union of the front and back visible rectangles.
//  - Each highlight part's visible rectangle is its own card part's rectangle grown by the same thickness on all four
//    sides, so it is concentric with it and the outline is even.
//  - CardRigRecenter is what gets a prefab there; the last test proves it does, from a deliberately misaligned rig.
public class HandHighlightAlignmentTests
{
    private static string HandPath => CardRigRecenter.HandPrefabPath;
    private const float Tolerance = 5e-5f; // 0.05 mm; one alpha texel is ~0.3 mm
    private const float TexelSlack = 4.5e-4f; // a dealt card may sit one texel off the atlas-wide union

    private static readonly string[] Parts = { "Back", "FrontBlank" };

    private struct CardInfo
    {
        public Transform card;
        public Transform[] bones;
        public Vector3 axisA, axisB;
    }

    private static CardInfo Card(GameObject root, int index)
    {
        var hand = root.GetComponent<GrabbableHand>();
        Assert.IsNotNull(hand, "Hand.prefab has no GrabbableHand");
        return new CardInfo
        {
            card = root.transform.Find("Card" + index),
            bones = index == 0 ? hand.peekBones0 : hand.peekBones1,
            axisA = index == 0 ? hand.peekAxisA0 : hand.peekAxisA1,
            axisB = index == 0 ? hand.peekAxisB0 : hand.peekAxisB1,
        };
    }

    private static CardSilhouette.Rect2 Measure(Transform root, string path, CardInfo c)
    {
        Transform t = root.Find(path);
        Assert.IsNotNull(t, path + " missing");
        CardSilhouette.Rect2 rect;
        Assert.IsTrue(CardSilhouette.TryMeasure(t.GetComponent<SkinnedMeshRenderer>(), c.card, c.axisA, c.axisB,
            CardSilhouette.DefaultCutoff, out rect), path + " has no opaque pixels");
        return rect;
    }

    private static void WithHand(System.Action<GameObject> body)
    {
        GameObject root = PrefabUtility.LoadPrefabContents(HandPath);
        try { body(root); }
        finally { PrefabUtility.UnloadPrefabContents(root); }
    }

    private static void AssertRigMatchesSilhouette(GameObject root, int cardIndex)
    {
        CardInfo c = Card(root, cardIndex);
        CardSilhouette.Rect2 union = CardRigRecenter.MeasureRig(c.card, c.axisA, c.axisB);

        Vector2 gridMin = CardSilhouette.Project(c.bones[0].localPosition, c.axisA, c.axisB);
        Vector2 gridMax = CardSilhouette.Project(c.bones[c.bones.Length - 1].localPosition, c.axisA, c.axisB);
        string who = "Card" + cardIndex;
        Assert.AreEqual(union.min.x, gridMin.x, Tolerance, who + " rig edge (a min)");
        Assert.AreEqual(union.min.y, gridMin.y, Tolerance, who + " rig edge (b min)");
        Assert.AreEqual(union.max.x, gridMax.x, Tolerance, who + " rig edge (a max)");
        Assert.AreEqual(union.max.y, gridMax.y, Tolerance, who + " rig edge (b max)");

        // interior bones sit on the even grid, so the middle bone is the visual center
        Vector2 middle = CardSilhouette.Project(c.bones[7].localPosition, c.axisA, c.axisB);
        Assert.AreEqual(union.Center.x, middle.x, Tolerance, who + " middle bone (a)");
        Assert.AreEqual(union.Center.y, middle.y, Tolerance, who + " middle bone (b)");
    }

    // The face a highlight part outlines, as rendered now: Front (union of its atlas cells) for the top, Back below.
    private static CardSilhouette.Rect2 MeasureFace(Transform root, int cardIndex, string highlightPart, CardInfo c, bool perCell, out CardSilhouette.Rect2[] cells)
    {
        cells = null;
        string face = CardRigRecenter.FaceOutlinedBy(highlightPart);
        if (face != "Front")
            return Measure(root, "Card" + cardIndex + "/" + face, c);
        var smr = root.Find("Card" + cardIndex + "/Front").GetComponent<SkinnedMeshRenderer>();
        cells = CardSilhouette.MeasureAtlasCells(smr.sharedMesh, CardSilhouette.RestLocalVertices(smr, c.card),
            CardSilhouette.MainMaterial(smr), c.axisA, c.axisB, CardSilhouette.DefaultCutoff,
            CardSilhouette.AtlasColumns, CardSilhouette.AtlasRows);
        return CardSilhouette.Union(cells);
    }

    private static void AssertOutlineIsEven(GameObject root, int cardIndex, string set, float thickness)
    {
        CardInfo c = Card(root, cardIndex);
        foreach (string part in Parts)
        {
            CardSilhouette.Rect2[] cells;
            CardSilhouette.Rect2 card = MeasureFace(root.transform, cardIndex, part, c, false, out cells);
            CardSilhouette.Rect2 outline = Measure(root.transform, set + "/HighlightCard" + cardIndex + "/" + part, c);
            string who = set + "/HighlightCard" + cardIndex + "/" + part;
            Assert.AreEqual(thickness, card.min.x - outline.min.x, Tolerance, who + " margin, a min side");
            Assert.AreEqual(thickness, outline.max.x - card.max.x, Tolerance, who + " margin, a max side");
            Assert.AreEqual(thickness, card.min.y - outline.min.y, Tolerance, who + " margin, b min side");
            Assert.AreEqual(thickness, outline.max.y - card.max.y, Tolerance, who + " margin, b max side");

            // any single dealt card differs from the union by at most a texel (~0.35 mm); the outline may not be
            // visibly lopsided on it
            if (cells == null) continue;
            for (int i = 0; i < cells.Length; i++)
            {
                float left = cells[i].min.x - outline.min.x;
                float right = outline.max.x - cells[i].max.x;
                Assert.AreEqual(left, right, TexelSlack, who + " atlas cell " + i + " left/right margins");
                Assert.AreEqual(outline.max.y - cells[i].max.y, cells[i].min.y - outline.min.y, TexelSlack,
                    who + " atlas cell " + i + " top/bottom margins");
            }
        }
    }

    // ---- the saved prefab ----

    [Test]
    public void Hand_RigGridSpansTheVisibleCard([Values(0, 1)] int cardIndex)
    {
        WithHand(root => AssertRigMatchesSilhouette(root, cardIndex));
    }

    [Test]
    public void Hand_HandHighlightHugsEachCardPartEvenly([Values(0, 1)] int cardIndex)
    {
        WithHand(root => AssertOutlineIsEven(root, cardIndex, "HighlightHand", CardRigRecenter.HandOutlineThickness));
    }

    [Test]
    public void Hand_WinnerHighlightHugsEachCardPartEvenly([Values(0, 1)] int cardIndex)
    {
        WithHand(root => AssertOutlineIsEven(root, cardIndex, "Highlight", CardRigRecenter.WinnerOutlineThickness));
    }

    [Test]
    public void Hand_HighlightsFollowTheSameBonesAsTheirCard([Values(0, 1)] int cardIndex)
    {
        WithHand(root =>
        {
            CardInfo c = Card(root, cardIndex);
            foreach (string set in new[] { "HighlightHand", "Highlight" })
            foreach (string part in Parts)
            {
                var smr = root.transform.Find(set + "/HighlightCard" + cardIndex + "/" + part).GetComponent<SkinnedMeshRenderer>();
                CollectionAssert.AreEqual(c.bones, smr.bones, set + " " + part + " bones");
                foreach (BoneWeight w in smr.sharedMesh.boneWeights)
                    Assert.AreEqual(1f, w.weight0 + w.weight1 + w.weight2 + w.weight3, 1e-4f);
            }
        });
    }

    // ---- the fix itself ----

    [Test]
    public void Recenter_FixesAMisalignedRig()
    {
        // Work on a scratch copy: the source meshes are shared assets, so snapshot and restore them around the run.
        var meshes = new System.Collections.Generic.List<Mesh>();
        var snapshots = new System.Collections.Generic.List<Mesh>();
        WithHand(root =>
        {
            foreach (var smr in root.GetComponentsInChildren<SkinnedMeshRenderer>(true))
            {
                if (smr.sharedMesh == null || meshes.Contains(smr.sharedMesh)) continue;
                meshes.Add(smr.sharedMesh);
                snapshots.Add(Object.Instantiate(smr.sharedMesh));
            }

            try
            {
                // knock every hole-card bone off by 2 mm so the rig is provably wrong
                for (int cardIndex = 0; cardIndex < 2; cardIndex++)
                {
                    CardInfo c = Card(root, cardIndex);
                    foreach (Transform bone in c.bones)
                        bone.localPosition += c.axisA * 0.002f + c.axisB * -0.002f;
                }
                Assert.Throws<AssertionException>(() => AssertRigMatchesSilhouette(root, 0), "setup should misalign the rig");

                CardRigRecenter.Apply(root);

                for (int cardIndex = 0; cardIndex < 2; cardIndex++)
                {
                    AssertRigMatchesSilhouette(root, cardIndex);
                    AssertOutlineIsEven(root, cardIndex, "HighlightHand", CardRigRecenter.HandOutlineThickness);
                    AssertOutlineIsEven(root, cardIndex, "Highlight", CardRigRecenter.WinnerOutlineThickness);
                }
            }
            finally
            {
                for (int i = 0; i < meshes.Count; i++)
                {
                    meshes[i].bindposes = snapshots[i].bindposes;
                    meshes[i].boneWeights = snapshots[i].boneWeights;
                    Object.DestroyImmediate(snapshots[i]);
                }
            }
        });
    }
}
