using UnityEditor;
using UnityEngine;

/// <summary>
/// CORRECTION AUTOMATIQUE CS2006 - S'exécute automatiquement au démarrage d'Unity
/// </summary>
[InitializeOnLoad]
public class AutoFixCS2006OnStart
{
    static AutoFixCS2006OnStart()
    {
        // Attendre que Unity soit prêt
        EditorApplication.delayCall += FixCS2006Issue;
    }
    
    static void FixCS2006Issue()
    {
        Debug.Log("🔧 [AUTO-FIX] Correction CS2006 en cours...");
        
        // Nettoyer TOUTES les plateformes
        BuildTargetGroup[] allTargets = new BuildTargetGroup[]
        {
            BuildTargetGroup.Standalone,
            BuildTargetGroup.WebGL,
            BuildTargetGroup.Android,
            BuildTargetGroup.iOS,
            BuildTargetGroup.WSA
        };
        
        bool isFixed = false;
        
        foreach (var target in allTargets)
        {
            try
            {
#if UNITY_2023_1_OR_NEWER
                var namedTarget = UnityEditor.Build.NamedBuildTarget.FromBuildTargetGroup(target);
                string current = PlayerSettings.GetScriptingDefineSymbols(namedTarget);
                
                if (!string.IsNullOrEmpty(current) && current.Trim() == "")
                {
                    // Symbole vide mais pas null - CORRECTION
                    PlayerSettings.SetScriptingDefineSymbols(namedTarget, "");
                    isFixed = true;
                    Debug.Log($"  ✓ {target}: symbole vide corrigé");
                }
                else if (string.IsNullOrEmpty(current))
                {
                    // Forcer à vide par sécurité
                    PlayerSettings.SetScriptingDefineSymbols(namedTarget, "");
                }
#else
                string current = PlayerSettings.GetScriptingDefineSymbolsForGroup(target);
                
                if (!string.IsNullOrEmpty(current) && current.Trim() == "")
                {
                    PlayerSettings.SetScriptingDefineSymbolsForGroup(target, "");
                    isFixed = true;
                    Debug.Log($"  ✓ {target}: symbole vide corrigé");
                }
                else if (string.IsNullOrEmpty(current))
                {
                    PlayerSettings.SetScriptingDefineSymbolsForGroup(target, "");
                }
#endif
            }
            catch (System.Exception e)
            {
                Debug.LogWarning($"  ⚠ {target}: {e.Message}");
            }
        }
        
        if (isFixed)
        {
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
            Debug.Log("✅ [AUTO-FIX] Correction appliquée ! Recompilation en cours...");
        }
        else
        {
            Debug.Log("✅ [AUTO-FIX] Aucune correction nécessaire");
        }
    }
}


