using UnityEngine;

/// <summary>
/// S'assure que tous les Managers essentiels existent dans la scène
/// À placer sur un GameObject dans la scène Menu (et autres scènes de départ)
/// </summary>
public class ManagersInitializer : MonoBehaviour
{
    [Header("Configuration")]
    [SerializeField] private bool initializeOnAwake = true;
    [SerializeField] private bool createManagersIfMissing = true;
    
    [Header("Prefabs (optionnel)")]
    [SerializeField] private GameObject generalConfigManagerPrefab;
    [SerializeField] private GameObject levelManagerPrefab;
    
    void Awake()
    {
        if (initializeOnAwake)
        {
            InitializeManagers();
        }
    }
    
    void InitializeManagers()
    {
        DebugLogger.Log("═══ Initialisation des Managers ═══", "ManagersInitializer");
        
        // 1. GeneralConfigManager
        if (GeneralConfigManager.Instance == null)
        {
            DebugLogger.LogWarning("GeneralConfigManager manquant - création automatique", "ManagersInitializer");
            CreateGeneralConfigManager();
        }
        else
        {
            DebugLogger.LogInfo("GeneralConfigManager trouvé ✓", "ManagersInitializer");
        }
        
        // 2. LevelManager
        if (LevelManager.Instance == null)
        {
            DebugLogger.LogWarning("LevelManager manquant - création automatique", "ManagersInitializer");
            CreateLevelManager();
        }
        else
        {
            DebugLogger.LogInfo("LevelManager trouvé ✓", "ManagersInitializer");
        }
        
        DebugLogger.Log("═══ Managers initialisés ═══", "ManagersInitializer");
    }
    
    void CreateGeneralConfigManager()
    {
        GameObject go;
        
        if (generalConfigManagerPrefab != null)
        {
            go = Instantiate(generalConfigManagerPrefab);
            go.name = "GeneralConfigManager";
        }
        else
        {
            go = new GameObject("GeneralConfigManager");
            go.AddComponent<GeneralConfigManager>();
        }
        
        DontDestroyOnLoad(go);
        DebugLogger.LogInfo("GeneralConfigManager créé", "ManagersInitializer");
    }
    
    void CreateLevelManager()
    {
        GameObject go;
        
        if (levelManagerPrefab != null)
        {
            go = Instantiate(levelManagerPrefab);
            go.name = "LevelManager";
        }
        else
        {
            go = new GameObject("LevelManager");
            go.AddComponent<LevelManager>();
        }
        
        DontDestroyOnLoad(go);
        DebugLogger.LogInfo("LevelManager créé", "ManagersInitializer");
    }
    
    /// <summary>
    /// Méthode publique pour initialiser manuellement
    /// </summary>
    public void ManualInitialize()
    {
        InitializeManagers();
    }
}

