using UnityEngine;
using UnityEditor;
using System.Linq;

/// <summary>
/// Unity Editor script to check and fix Build Settings for scene loading
/// </summary>
public class SceneBuildSettingsChecker : MonoBehaviour
{
    [Header("Scene Build Settings Checker")]
    [TextArea(3, 5)]
    public string instructions = "This script checks if required scenes are in Build Settings.\nUse the buttons below to check and fix issues.";

    [ContextMenu("Check Build Settings")]
    public void CheckBuildSettings()
    {
        Debug.Log("=== Checking Build Settings ===");

#if UNITY_EDITOR
        // Get current build settings
        var scenes = EditorBuildSettings.scenes;
        
        Debug.Log($"Current scenes in Build Settings: {scenes.Length}");
        
        foreach (var scene in scenes)
        {
            Debug.Log($"  - {scene.path} (enabled: {scene.enabled})");
        }
        
        // Check specific scenes we need
        string[] requiredScenes = { "TownSceen", "MapScene2" };
        
        foreach (string sceneName in requiredScenes)
        {
            bool found = scenes.Any(s => s.path.Contains(sceneName) && s.enabled);
            
            if (found)
            {
                Debug.Log($"✅ {sceneName} found in Build Settings");
            }
            else
            {
                Debug.LogError($"❌ {sceneName} NOT found in Build Settings!");
                Debug.LogError($"   Add Assets/Scenes/{sceneName}.unity to Build Settings");
            }
        }
        
        Debug.Log("=== Build Settings Check Complete ===");
        Debug.Log("To fix: Go to File > Build Settings and drag scene files into the list");
#else
        Debug.LogWarning("Build Settings can only be checked in Editor mode");
#endif
    }

    [ContextMenu("Auto Fix Build Settings")]
    public void AutoFixBuildSettings()
    {
#if UNITY_EDITOR
        Debug.Log("=== Auto-fixing Build Settings ===");
        
        // Define scenes that should be in build settings
        string[] sceneNames = { 
            "TitleScreenScene", 
            "MainTeamSelectScene", 
            "MapScene2", 
            "TownSceen", 
            "BattleScene",
            "BattleSetupMenu"
        };
        
        var currentScenes = EditorBuildSettings.scenes.ToList();
        bool addedAny = false;
        
        foreach (string sceneName in sceneNames)
        {
            string scenePath = $"Assets/Scenes/{sceneName}.unity";
            
            // Check if scene already exists in build settings
            bool alreadyExists = currentScenes.Any(s => s.path == scenePath);
            
            if (!alreadyExists)
            {
                // Check if scene file exists
                if (System.IO.File.Exists(scenePath))
                {
                    var newScene = new EditorBuildSettingsScene(scenePath, true);
                    currentScenes.Add(newScene);
                    addedAny = true;
                    Debug.Log($"✅ Added {sceneName} to Build Settings");
                }
                else
                {
                    Debug.LogWarning($"⚠️ Scene file not found: {scenePath}");
                }
            }
            else
            {
                Debug.Log($"✅ {sceneName} already in Build Settings");
            }
        }
        
        if (addedAny)
        {
            EditorBuildSettings.scenes = currentScenes.ToArray();
            Debug.Log("🎯 Build Settings updated successfully!");
            Debug.Log("Scenes are now ready for SceneManager.LoadScene()");
        }
        else
        {
            Debug.Log("ℹ️ No changes needed - all scenes already in Build Settings");
        }
        
        // Re-check to confirm
        CheckBuildSettings();
#else
        Debug.LogWarning("Build Settings can only be modified in Editor mode");
#endif
    }

    [ContextMenu("Test Scene Loading")]
    public void TestSceneLoading()
    {
        Debug.Log("=== Testing Scene Loading ===");

        // Test if we can load TownSceen
        string sceneName = "TownSceen";

        try
        {
            // This would actually load the scene, so we'll just check if it would work
            Debug.Log($"Attempting to load scene: {sceneName}");

            // Check Application.CanStreamedLevelBeLoaded for older Unity versions
            // or just try the load directly
#if UNITY_EDITOR
            var scenes = UnityEditor.EditorBuildSettings.scenes;
            bool foundInBuild = scenes.Any(s => s.path.Contains(sceneName) && s.enabled);
            
            if (foundInBuild)
            {
                Debug.Log($"✅ Scene {sceneName} should load successfully");
                Debug.Log("You can now test entering settlements!");
            }
            else
            {
                Debug.LogError($"❌ Scene {sceneName} not properly configured in Build Settings");
            }
#endif
        }
        catch (System.Exception e)
        {
            Debug.LogError($"❌ Scene loading test failed: {e.Message}");
        }
    }

    void OnGUI()
    {
        GUILayout.BeginArea(new Rect(10, Screen.height - 200, 300, 180));
        GUILayout.BeginVertical("box");

        GUILayout.Label("Scene Build Settings Fixer", new GUIStyle(GUI.skin.label) { fontSize = 12, fontStyle = FontStyle.Bold });

        if (GUILayout.Button("Check Build Settings"))
        {
            CheckBuildSettings();
        }

        if (GUILayout.Button("Auto Fix Build Settings"))
        {
            AutoFixBuildSettings();
        }

        if (GUILayout.Button("Test Scene Loading"))
        {
            TestSceneLoading();
        }

        GUILayout.Space(5);
        GUILayout.Label("Manual Fix:", new GUIStyle(GUI.skin.label) { fontSize = 10, fontStyle = FontStyle.Bold });
        GUILayout.Label("File > Build Settings", new GUIStyle(GUI.skin.label) { fontSize = 10 });
        GUILayout.Label("Drag scenes into list", new GUIStyle(GUI.skin.label) { fontSize = 10 });

        GUILayout.EndVertical();
        GUILayout.EndArea();
    }
}
