using UnityEngine;

/// <summary>
/// Setup script for the enhanced perception and event system
/// Automatically adds required components and configures the spottable event system
/// </summary>
public class PerceptionEventSystemSetup : MonoBehaviour
{
    [Header("Auto Setup")]
    [SerializeField] private bool autoSetupOnStart = true;

    [Header("Event Marker Settings")]
    [SerializeField] private GameObject eventMarkerPrefab;
    [SerializeField] private Material eventMarkerMaterial;
    [SerializeField] private Color eventMarkerColor = Color.red;
    [SerializeField] private int maxActiveMarkers = 5;

    [Header("Debug")]
    [SerializeField] private bool showSetupLogs = true;

    void Start()
    {
        if (autoSetupOnStart)
        {
            SetupPerceptionEventSystem();
        }
    }

    /// <summary>
    /// Sets up the perception and event system components
    /// </summary>
    [ContextMenu("Setup Perception Event System")]
    public void SetupPerceptionEventSystem()
    {
        if (showSetupLogs)
            Debug.Log("🔧 Setting up Perception Event System...");

        // Ensure TeamPerceptionVisualizer exists
        SetupPerceptionVisualizer();

        // Setup EventMarkerVisualizer
        SetupEventMarkerVisualizer();

        // Verify TravelEventSystem integration
        VerifyTravelEventSystem();

        if (showSetupLogs)
            Debug.Log("✅ Perception Event System setup complete!");
    }

    private void SetupPerceptionVisualizer()
    {
        var perceptionVisualizer = FindFirstObjectByType<TeamPerceptionVisualizer>();
        if (perceptionVisualizer == null)
        {
            // Find a suitable GameObject to add it to (prefer the one with SimpleTeamPlacement)
            var teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
            GameObject targetObject = teamPlacement?.gameObject ?? gameObject;

            perceptionVisualizer = targetObject.AddComponent<TeamPerceptionVisualizer>();
            if (showSetupLogs)
                Debug.Log($"✅ Added TeamPerceptionVisualizer to {targetObject.name}");
        }
        else if (showSetupLogs)
        {
            Debug.Log("✅ TeamPerceptionVisualizer already exists");
        }
    }

    private void SetupEventMarkerVisualizer()
    {
        var markerVisualizer = FindFirstObjectByType<EventMarkerVisualizer>();
        if (markerVisualizer == null)
        {
            // Find a suitable GameObject to add it to (prefer the one with TravelEventSystem)
            var eventSystem = FindFirstObjectByType<TravelEventSystem>();
            GameObject targetObject = eventSystem?.gameObject ?? gameObject;

            markerVisualizer = targetObject.AddComponent<EventMarkerVisualizer>();

            // Configure with our settings
            if (eventMarkerPrefab != null)
            {
                // Use reflection to set private fields since they're SerializeField
                var prefabField = markerVisualizer.GetType().GetField("eventMarkerPrefab",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                prefabField?.SetValue(markerVisualizer, eventMarkerPrefab);
            }

            if (eventMarkerMaterial != null)
            {
                var materialField = markerVisualizer.GetType().GetField("eventMarkerMaterial",
                    System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                materialField?.SetValue(markerVisualizer, eventMarkerMaterial);
            }

            var colorField = markerVisualizer.GetType().GetField("eventMarkerColor",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            colorField?.SetValue(markerVisualizer, eventMarkerColor);

            var maxMarkersField = markerVisualizer.GetType().GetField("maxActiveMarkers",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            maxMarkersField?.SetValue(markerVisualizer, maxActiveMarkers);

            if (showSetupLogs)
                Debug.Log($"✅ Added EventMarkerVisualizer to {targetObject.name}");
        }
        else if (showSetupLogs)
        {
            Debug.Log("✅ EventMarkerVisualizer already exists");
        }
    }

    private void VerifyTravelEventSystem()
    {
        var eventSystem = FindFirstObjectByType<TravelEventSystem>();
        if (eventSystem == null)
        {
            if (showSetupLogs)
                Debug.LogWarning("⚠️ No TravelEventSystem found. Please add one to use the event system.");
            return;
        }

        if (showSetupLogs)
            Debug.Log("✅ TravelEventSystem found and should integrate automatically");
    }

    /// <summary>
    /// Creates example spottable events for testing
    /// </summary>
    [ContextMenu("Create Example Spottable Events")]
    public void CreateExampleSpottableEvents()
    {
        if (showSetupLogs)
            Debug.Log("🎭 Creating example spottable events...");

        // This would create ScriptableObject assets in the project
        // For now, just log what would be created
        Debug.Log("📋 Example events to create:");
        Debug.Log("- SpottableSkeletonPatrol: Skeleton warriors that can be spotted and avoided");
        Debug.Log("- SpottableBanditCamp: Bandit camps visible from a distance");
        Debug.Log("- SpottableTreasureCache: Hidden treasure that can be spotted with good perception");

        Debug.Log("💡 Tip: Right-click in Project → Create → RPG → Travel Events → Spottable → [Event Type]");
    }

    /// <summary>
    /// Shows current system status
    /// </summary>
    [ContextMenu("Show System Status")]
    public void ShowSystemStatus()
    {
        Debug.Log("=== Perception Event System Status ===");

        var perceptionVisualizer = FindFirstObjectByType<TeamPerceptionVisualizer>();
        Debug.Log($"TeamPerceptionVisualizer: {(perceptionVisualizer ? "✅ Found" : "❌ Missing")}");

        var markerVisualizer = FindFirstObjectByType<EventMarkerVisualizer>();
        Debug.Log($"EventMarkerVisualizer: {(markerVisualizer ? "✅ Found" : "❌ Missing")}");

        var eventSystem = FindFirstObjectByType<TravelEventSystem>();
        Debug.Log($"TravelEventSystem: {(eventSystem ? "✅ Found" : "❌ Missing")}");

        var teamPlacement = FindFirstObjectByType<SimpleTeamPlacement>();
        Debug.Log($"SimpleTeamPlacement: {(teamPlacement ? "✅ Found" : "❌ Missing")}");

        if (markerVisualizer != null)
        {
            // Use reflection to get active marker count
            var method = markerVisualizer.GetType().GetMethod("GetActiveMarkerCount");
            if (method != null)
            {
                int activeMarkers = (int)method.Invoke(markerVisualizer, null);
                Debug.Log($"Active Event Markers: {activeMarkers}");
            }
        }

        Debug.Log("========================================");
    }
}
