using UnityEditor;
using UnityEngine;

// Re-fits the hole cards' peek rig and their highlight outlines to what is actually visible.
//
// The card quads are padded around the printed card, so a rig built from mesh bounds (CardPeekRigGenerator) puts its
// edge bones outside the card and lets the outline drift. The truth is the texture's alpha mask:
//   1. the visible rectangle of each face is measured from that mask (CardSilhouette). The shown face is Front, a
//      cell of card_atlas.png; FrontBlank and Back use default_card.png, whose masks sit ~0.5 mm off-center in
//      opposite directions and are smaller than Front's,
//   2. the 3x5 bone grid is laid exactly over the union of those rectangles,
//   3. each highlight part is re-skinned so its own mask lands a uniform thickness outside the face it outlines
//      (top side: Front, underside: Back).
// Meshes keep their vertices; only bone weights and bind poses are rewritten, so it is safe to re-run.
public static class CardRigRecenter
{
    public static string HandPrefabPath => HoldemPaths.Asset("DevPrefabs/Hand.prefab");
    public const float HandOutlineThickness = 0.0025f;
    public const float WinnerOutlineThickness = 0.0042f;
    private const int Columns = 3;
    private const int Rows = 5;

    private static readonly string[] CardParts = { "Back", "Front", "FrontBlank" };
    private static readonly string[] HighlightParts = { "Back", "FrontBlank" };

    [MenuItem("VrchatHoldem/Recenter Card Peek Rig")]
    public static void Recenter()
    {
        GameObject root = PrefabUtility.LoadPrefabContents(HandPrefabPath);
        try
        {
            Apply(root);
            PrefabUtility.SaveAsPrefabAsset(root, HandPrefabPath);
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(root);
        }
        AssetDatabase.SaveAssets();
        Debug.Log("[CardRigRecenter] Recentered the hole-card rigs and highlights on their alpha silhouettes.");
    }

    // Works on an already loaded prefab root; the caller decides whether to save it.
    public static void Apply(GameObject root)
    {
        GrabbableHand hand = root.GetComponent<GrabbableHand>();
        if (hand == null)
            throw new System.InvalidOperationException("Hand prefab has no GrabbableHand.");

        for (int cardIndex = 0; cardIndex < 2; cardIndex++)
        {
            Transform card = root.transform.Find("Card" + cardIndex);
            Transform[] bones = cardIndex == 0 ? hand.peekBones0 : hand.peekBones1;
            Vector3 axisA = cardIndex == 0 ? hand.peekAxisA0 : hand.peekAxisA1;
            Vector3 axisB = cardIndex == 0 ? hand.peekAxisB0 : hand.peekAxisB1;
            if (card == null || bones == null || bones.Length != Columns * Rows)
                throw new System.InvalidOperationException("Card" + cardIndex + " has no " + Columns * Rows + "-bone rig.");

            CardSilhouette.Rect2 rig = MeasureRig(card, axisA, axisB);
            MoveBones(bones, axisA, axisB, rig);

            foreach (string part in CardParts)
            {
                Transform partTransform = card.Find(part);
                if (partTransform == null)
                    continue;
                Rebind(partTransform.GetComponent<SkinnedMeshRenderer>(), card, bones, axisA, axisB, rig, null, 0f);
            }

            RebindHighlight(root, "HighlightHand", cardIndex, card, bones, axisA, axisB, rig, HandOutlineThickness);
            RebindHighlight(root, "Highlight", cardIndex, card, bones, axisA, axisB, rig, WinnerOutlineThickness);
        }
    }

    // Union of every face's visible rectangle (Front over all its atlas cells, FrontBlank, Back). Measured from where
    // each mesh sits in the card's space, not from where the bones currently put it, so a misplaced rig cannot skew it.
    public static CardSilhouette.Rect2 MeasureRig(Transform card, Vector3 axisA, Vector3 axisB)
    {
        CardSilhouette.Rect2 union = MeasureFace(card, "Front", axisA, axisB);
        union = Union(union, MeasureFace(card, "FrontBlank", axisA, axisB));
        return Union(union, MeasureFace(card, "Back", axisA, axisB));
    }

    // What the player sees of one card part. The shown face is Front, whose silhouette depends on the atlas cell, so
    // it is the union over all cells; FrontBlank and Back have a single mask each.
    public static CardSilhouette.Rect2 MeasureFace(Transform card, string part, Vector3 axisA, Vector3 axisB)
    {
        SkinnedMeshRenderer smr = card.Find(part).GetComponent<SkinnedMeshRenderer>();
        Matrix4x4 meshToCard = Matrix4x4.TRS(smr.transform.localPosition, smr.transform.localRotation, smr.transform.localScale);
        Vector3[] vertices = smr.sharedMesh.vertices;
        for (int i = 0; i < vertices.Length; i++)
            vertices[i] = meshToCard.MultiplyPoint3x4(vertices[i]);

        if (part == "Front")
            return CardSilhouette.Union(CardSilhouette.MeasureAtlasCells(smr.sharedMesh, vertices,
                CardSilhouette.MainMaterial(smr), axisA, axisB, CardSilhouette.DefaultCutoff,
                CardSilhouette.AtlasColumns, CardSilhouette.AtlasRows));

        CardSilhouette.Rect2 rect;
        if (!CardSilhouette.TryMeasure(smr.sharedMesh, vertices, CardSilhouette.MainMaterial(smr), axisA, axisB,
                CardSilhouette.DefaultCutoff, out rect))
            throw new System.InvalidOperationException(card.name + "/" + part + " has no opaque pixels to measure.");
        return rect;
    }

    // The face a highlight part outlines: the shown Front for the top side, the Back for the underside.
    public static string FaceOutlinedBy(string highlightPart)
    {
        return highlightPart == "FrontBlank" ? "Front" : highlightPart;
    }

    private static CardSilhouette.Rect2 Union(CardSilhouette.Rect2 a, CardSilhouette.Rect2 b)
    {
        return new CardSilhouette.Rect2 { min = Vector2.Min(a.min, b.min), max = Vector2.Max(a.max, b.max) };
    }

    private static void MoveBones(Transform[] bones, Vector3 axisA, Vector3 axisB, CardSilhouette.Rect2 rect)
    {
        Vector3 normal = Vector3.Cross(axisA, axisB).normalized;
        for (int row = 0; row < Rows; row++)
        {
            for (int column = 0; column < Columns; column++)
            {
                Transform bone = bones[row * Columns + column];
                float along = Vector3.Dot(bone.localPosition, normal);
                bone.localPosition = axisA * Mathf.Lerp(rect.min.x, rect.max.x, column / (float)(Columns - 1)) +
                    axisB * Mathf.Lerp(rect.min.y, rect.max.y, row / (float)(Rows - 1)) + normal * along;
            }
        }
    }

    private static void RebindHighlight(GameObject root, string setName, int cardIndex, Transform card, Transform[] bones,
        Vector3 axisA, Vector3 axisB, CardSilhouette.Rect2 rig, float thickness)
    {
        Transform set = root.transform.Find(setName + "/HighlightCard" + cardIndex);
        if (set == null)
            throw new System.InvalidOperationException(setName + "/HighlightCard" + cardIndex + " is missing.");
        // a highlight part's mesh space is only "the card's" while its parent sits exactly on the card
        if ((set.localPosition - card.localPosition).sqrMagnitude > 1e-10f ||
            Quaternion.Angle(set.localRotation, card.localRotation) > 0.001f)
            throw new System.InvalidOperationException(set.name + " is not aligned with " + card.name + ".");

        foreach (string part in HighlightParts)
        {
            Transform partTransform = set.Find(part);
            if (partTransform == null)
                continue;
            Rebind(partTransform.GetComponent<SkinnedMeshRenderer>(), card, bones, axisA, axisB, rig, set, thickness);
        }
    }

    // Rewrites bind poses and bone weights of one skinned part. For a highlight (outlineParent != null) the part's
    // mask rectangle is carried onto the face it outlines, grown by 'thickness' on every side.
    private static void Rebind(SkinnedMeshRenderer smr, Transform card, Transform[] bones, Vector3 axisA, Vector3 axisB,
        CardSilhouette.Rect2 rig, Transform outlineParent, float thickness)
    {
        Mesh mesh = smr.sharedMesh;
        Vector3[] vertices = mesh.vertices;

        // mesh space -> card-local space. Skinning ignores the renderer's own transform, so a highlight part uses the
        // matching card part's placement (its own local pose may have been nudged since it was skinned) and lies
        // flat in the card's plane, as it was generated.
        Transform frame = outlineParent == null ? smr.transform : card.Find(smr.name);
        if (frame == null || frame.parent != card)
            throw new System.InvalidOperationException(smr.name + " has no card part to take its placement from.");
        Matrix4x4 meshToCard = Matrix4x4.TRS(frame.localPosition, frame.localRotation, frame.localScale);
        Vector3 normal = Vector3.Cross(axisA, axisB).normalized;

        Vector3[] baseLocal = new Vector3[vertices.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            Vector3 p = meshToCard.MultiplyPoint3x4(vertices[i]);
            baseLocal[i] = outlineParent == null ? p : p - normal * Vector3.Dot(p, normal);
        }

        Matrix4x4 outline = Matrix4x4.identity;
        if (outlineParent != null)
        {
            CardSilhouette.Rect2 own;
            if (!CardSilhouette.TryMeasure(mesh, baseLocal, CardSilhouette.MainMaterial(smr), axisA, axisB,
                    CardSilhouette.DefaultCutoff, out own))
                throw new System.InvalidOperationException(smr.name + " has no opaque pixels to measure.");
            CardSilhouette.Rect2 face = MeasureFace(card, FaceOutlinedBy(smr.name), axisA, axisB);
            face.min -= new Vector2(thickness, thickness);
            face.max += new Vector2(thickness, thickness);
            outline = FitRect(own, face, axisA, axisB);
        }

        if (outlineParent != null)
        {
            Matrix4x4 flatten = Matrix4x4.identity;
            for (int row = 0; row < 3; row++)
                for (int column = 0; column < 3; column++)
                    flatten[row, column] -= Component(normal, row) * Component(normal, column);
            meshToCard = flatten * meshToCard;
        }
        Matrix4x4 fullMap = outline * meshToCard;
        BoneWeight[] weights = new BoneWeight[vertices.Length];
        for (int i = 0; i < vertices.Length; i++)
            weights[i] = GridWeights(fullMap.MultiplyPoint3x4(vertices[i]), axisA, axisB, rig);

        Matrix4x4[] bindposes = new Matrix4x4[bones.Length];
        for (int i = 0; i < bones.Length; i++)
            bindposes[i] = bones[i].worldToLocalMatrix * card.localToWorldMatrix * fullMap;

        mesh.boneWeights = weights;
        mesh.bindposes = bindposes;
        smr.bones = bones;
        smr.rootBone = card;
        EditorUtility.SetDirty(mesh);
        EditorUtility.SetDirty(smr);
    }

    // Card-local transform that carries rectangle 'from' exactly onto rectangle 'to' (scale and shift in a and b).
    private static Matrix4x4 FitRect(CardSilhouette.Rect2 from, CardSilhouette.Rect2 to, Vector3 axisA, Vector3 axisB)
    {
        float scaleA = to.Size.x / from.Size.x;
        float scaleB = to.Size.y / from.Size.y;
        float shiftA = to.min.x - from.min.x * scaleA;
        float shiftB = to.min.y - from.min.y * scaleB;
        Matrix4x4 m = Matrix4x4.identity;
        for (int row = 0; row < 3; row++)
        {
            for (int column = 0; column < 3; column++)
            {
                m[row, column] = (row == column ? 1f : 0f) + (scaleA - 1f) * Component(axisA, row) * Component(axisA, column) +
                    (scaleB - 1f) * Component(axisB, row) * Component(axisB, column);
            }
            m[row, 3] = shiftA * Component(axisA, row) + shiftB * Component(axisB, row);
        }
        return m;
    }

    private static float Component(Vector3 v, int index)
    {
        return index == 0 ? v.x : (index == 1 ? v.y : v.z);
    }

    private static BoneWeight GridWeights(Vector3 local, Vector3 axisA, Vector3 axisB, CardSilhouette.Rect2 rig)
    {
        float gridA = Mathf.InverseLerp(rig.min.x, rig.max.x, Vector3.Dot(local, axisA)) * (Columns - 1);
        float gridB = Mathf.InverseLerp(rig.min.y, rig.max.y, Vector3.Dot(local, axisB)) * (Rows - 1);
        int a0 = Mathf.Clamp(Mathf.FloorToInt(gridA), 0, Columns - 1);
        int b0 = Mathf.Clamp(Mathf.FloorToInt(gridB), 0, Rows - 1);
        int a1 = Mathf.Min(a0 + 1, Columns - 1);
        int b1 = Mathf.Min(b0 + 1, Rows - 1);
        float blendA = gridA - a0;
        float blendB = gridB - b0;
        return new BoneWeight
        {
            boneIndex0 = b0 * Columns + a0,
            boneIndex1 = b0 * Columns + a1,
            boneIndex2 = b1 * Columns + a0,
            boneIndex3 = b1 * Columns + a1,
            weight0 = (1f - blendA) * (1f - blendB),
            weight1 = blendA * (1f - blendB),
            weight2 = (1f - blendA) * blendB,
            weight3 = blendA * blendB
        };
    }
}
