using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEngine;

/// <summary>
/// Resizes the chip pools inside a table prefab (HoldemGame.prefab by default; its variants inherit).
/// Only prefab assets are edited, never a scene: the scene's tables pick the new chips up as plain prefab
/// instances, so WORLD.unity does not change. Growing clones the pool's own first chip, so mesh, collider, layer
/// and physics settings carry over; shrinking removes chips from the end. Before applying, pools whose Pool array
/// or chips are overridden by a scene instance or a prefab variant are reported (a resize would not reach them);
/// after applying, every pool derived from the prefab is checked to have the new size.
/// </summary>
public class PokerChipPoolSetupEditor : EditorWindow
{
    private static string DefaultPrefabPath => HoldemPaths.Asset("Prefabs/HoldemGame.prefab");

    private GameObject prefab;
    private readonly Dictionary<int, int> targetSizes = new Dictionary<int, int>();
    private string report = "";
    private Vector2 scroll;

    [MenuItem("Tools/Holdem/Chip Pool Sizes")]
    public static void ShowWindow()
    {
        GetWindow<PokerChipPoolSetupEditor>("Chip Pool Sizes");
    }

    private void OnEnable()
    {
        if (prefab == null) prefab = AssetDatabase.LoadAssetAtPath<GameObject>(DefaultPrefabPath);
        RefreshSizes();
    }

    private void OnGUI()
    {
        EditorGUILayout.HelpBox(
            "Edits the table prefab asset only. Scenes are never saved or modified; their tables follow the prefab.",
            MessageType.Info);
        EditorGUI.BeginChangeCheck();
        prefab = (GameObject)EditorGUILayout.ObjectField("Table Prefab", prefab, typeof(GameObject), false);
        if (EditorGUI.EndChangeCheck()) RefreshSizes();
        if (prefab == null || !EditorUtility.IsPersistent(prefab))
        {
            EditorGUILayout.HelpBox("Pick a prefab asset from the Project window.", MessageType.Warning);
            return;
        }

        foreach (int denomination in targetSizes.Keys.OrderBy(d => d).ToArray())
            targetSizes[denomination] = Mathf.Max(0, EditorGUILayout.IntField($"{denomination} chips", targetSizes[denomination]));

        EditorGUILayout.BeginHorizontal();
        string path = AssetDatabase.GetAssetPath(prefab);
        if (GUILayout.Button("Check")) report = Resize(path, targetSizes, false);
        if (GUILayout.Button("Apply"))
        {
            report = Resize(path, targetSizes, false);
            if (!report.Contains("BLOCKED")
                && EditorUtility.DisplayDialog("Resize chip pools", report + "\n\nApply to " + path + "?", "Apply", "Cancel"))
                report = Resize(path, targetSizes, true);
        }
        EditorGUILayout.EndHorizontal();

        scroll = EditorGUILayout.BeginScrollView(scroll);
        EditorGUILayout.HelpBox(report, MessageType.None);
        EditorGUILayout.EndScrollView();
    }

    private void RefreshSizes()
    {
        targetSizes.Clear();
        if (prefab == null) return;
        foreach (LocalObjectPool pool in ChipPools(prefab))
            targetSizes[pool.denomination] = pool.Pool == null ? 0 : pool.Pool.Length;
    }

    /// <summary>
    /// Checks (apply = false) or applies a resize of the prefab's chip pools, keyed by denomination. Returns a
    /// report; a check that finds overridden pools says BLOCKED and apply refuses to run.
    /// </summary>
    public static string Resize(string prefabPath, IDictionary<int, int> sizeByDenomination, bool apply)
    {
        var sb = new StringBuilder();
        GameObject asset = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
        if (asset == null) return "BLOCKED: no prefab at " + prefabPath;

        List<string> blockers = FindOverrides(prefabPath, asset);
        foreach (LocalObjectPool pool in ChipPools(asset))
        {
            int current = pool.Pool == null ? 0 : pool.Pool.Length;
            int target = sizeByDenomination.TryGetValue(pool.denomination, out int size) ? size : current;
            sb.AppendLine($"{pool.name} ({pool.denomination}): {current} -> {target}");
            if (target > 0 && current == 0) blockers.Add($"{pool.name} has no chip to clone");
            if (current != pool.transform.childCount) blockers.Add($"{pool.name}: Pool holds {current} chips but has {pool.transform.childCount} children");
        }
        foreach (string blocker in blockers) sb.AppendLine("BLOCKED: " + blocker);
        if (!apply || blockers.Count > 0) return sb.ToString();

        GameObject contents = PrefabUtility.LoadPrefabContents(prefabPath);
        try
        {
            foreach (LocalObjectPool pool in ChipPools(contents))
            {
                if (!sizeByDenomination.TryGetValue(pool.denomination, out int target)) continue;
                ResizePool(pool, target);
            }
            PrefabUtility.SaveAsPrefabAsset(contents, prefabPath);
        }
        finally
        {
            PrefabUtility.UnloadPrefabContents(contents);
        }

        sb.AppendLine("Applied. Verification:");
        sb.Append(Verify(prefabPath, sizeByDenomination));
        return sb.ToString();
    }

    private static void ResizePool(LocalObjectPool pool, int target)
    {
        var chips = new List<GameObject>(pool.Pool);
        if (chips.Count == target) return;
        GameObject template = chips[0];
        string prefix = template.name.Contains("_Chip_")
            ? template.name.Substring(0, template.name.IndexOf("_Chip_") + "_Chip_".Length)
            : pool.name + "_Chip_";

        while (chips.Count > target)
        {
            GameObject last = chips[chips.Count - 1];
            chips.RemoveAt(chips.Count - 1);
            Object.DestroyImmediate(last);
        }
        while (chips.Count < target)
        {
            GameObject chip = Object.Instantiate(template, pool.transform);
            chip.name = prefix + chips.Count.ToString("D3");
            chip.transform.localPosition = template.transform.localPosition;
            chip.transform.localRotation = template.transform.localRotation;
            chip.transform.localScale = template.transform.localScale;
            chip.SetActive(template.activeSelf);
            chips.Add(chip);
        }

        var serialized = new SerializedObject(pool);
        SerializedProperty array = serialized.FindProperty("Pool");
        array.arraySize = chips.Count;
        for (int i = 0; i < chips.Count; i++) array.GetArrayElementAtIndex(i).objectReferenceValue = chips[i];
        serialized.ApplyModifiedPropertiesWithoutUndo();
        CopyProxyToUdon(pool);
    }

    // Pools in the prefab and in any loaded scene or other prefab that derive from it, whose Pool array, backing
    // Udon data or chip children are overridden there: the prefab's new size would not reach them.
    private static List<string> FindOverrides(string prefabPath, GameObject asset)
    {
        var blockers = new List<string>();
        var sourcePools = new HashSet<LocalObjectPool>(ChipPools(asset));

        foreach (LocalObjectPool pool in Object.FindObjectsOfType<LocalObjectPool>(true))
            CheckDerivedPool(pool, prefabPath, sourcePools, "scene " + pool.gameObject.scene.name, blockers);

        foreach (string guid in AssetDatabase.FindAssets("t:Prefab"))
        {
            string path = AssetDatabase.GUIDToAssetPath(guid);
            if (path == prefabPath) continue;
            GameObject other = AssetDatabase.LoadAssetAtPath<GameObject>(path);
            if (other == null) continue;
            foreach (LocalObjectPool pool in other.GetComponentsInChildren<LocalObjectPool>(true))
                CheckDerivedPool(pool, prefabPath, sourcePools, path, blockers);
        }
        return blockers;
    }

    private static void CheckDerivedPool(LocalObjectPool pool, string prefabPath, HashSet<LocalObjectPool> sourcePools,
        string where, List<string> blockers)
    {
        LocalObjectPool source = PrefabUtility.GetCorrespondingObjectFromSourceAtPath(pool, prefabPath);
        if (source == null || !sourcePools.Contains(source)) return;

        foreach (PropertyModification modification in PrefabUtility.GetPropertyModifications(pool) ?? new PropertyModification[0])
        {
            // The modifications cover the whole instance; only those on this pool's GameObject matter.
            if (!(modification.target is Component component) || component.gameObject.name != source.gameObject.name) continue;
            bool onPool = component is LocalObjectPool && modification.propertyPath.StartsWith("Pool");
            bool onBacking = component.GetType().Name == "UdonBehaviour" && modification.propertyPath.Contains("PublicVariables");
            if (onPool || onBacking)
            {
                blockers.Add($"{where}: {pool.name} overrides {modification.propertyPath}");
                return;
            }
        }
        if (pool.transform.childCount != source.transform.childCount)
            blockers.Add($"{where}: {pool.name} has {pool.transform.childCount} chips, the prefab {source.transform.childCount}");
    }

    private static string Verify(string prefabPath, IDictionary<int, int> sizeByDenomination)
    {
        var sb = new StringBuilder();
        GameObject asset = AssetDatabase.LoadAssetAtPath<GameObject>(prefabPath);
        var sourcePools = new HashSet<LocalObjectPool>(ChipPools(asset));
        int checkedPools = 0;
        foreach (LocalObjectPool pool in Object.FindObjectsOfType<LocalObjectPool>(true))
        {
            LocalObjectPool source = PrefabUtility.GetCorrespondingObjectFromSourceAtPath(pool, prefabPath);
            if (source == null || !sourcePools.Contains(source)) continue;
            if (!sizeByDenomination.TryGetValue(pool.denomination, out int expected)) continue;
            checkedPools++;
            int length = pool.Pool == null ? 0 : pool.Pool.Length;
            bool ok = length == expected && pool.transform.childCount == expected && pool.Pool.All(chip => chip != null);
            sb.AppendLine($"  {pool.transform.root.name}/{pool.name}: Pool={length} children={pool.transform.childCount} {(ok ? "ok" : "MISMATCH")}");
        }
        sb.AppendLine($"  {checkedPools} scene pools checked");
        return sb.ToString();
    }

    // The pools that hold table chips (the calibration menu's small pool is not a table pool).
    private static IEnumerable<LocalObjectPool> ChipPools(GameObject root)
    {
        return root.GetComponentsInChildren<LocalObjectPool>(true)
            .Where(pool => pool.Pool != null && pool.transform.parent != null && pool.transform.parent.name == "PokerChipPools");
    }

    private static void CopyProxyToUdon(Component behaviour)
    {
        System.Type utility = System.AppDomain.CurrentDomain.GetAssemblies()
            .Select(assembly => assembly.GetType("UdonSharpEditor.UdonSharpEditorUtility"))
            .FirstOrDefault(type => type != null);
        MethodInfo copy = utility?.GetMethods(BindingFlags.Public | BindingFlags.Static)
            .FirstOrDefault(method => method.Name == "CopyProxyToUdon" && method.GetParameters().Length >= 1);
        if (copy == null) return;
        ParameterInfo[] parameters = copy.GetParameters();
        var arguments = new object[parameters.Length];
        arguments[0] = behaviour;
        for (int i = 1; i < parameters.Length; i++)
            arguments[i] = parameters[i].HasDefaultValue ? parameters[i].DefaultValue : null;
        copy.Invoke(null, arguments);
    }
}
