using UnityEngine;
using System.Linq;

/// <summary>
/// Simple debug script to help troubleshoot quest system issues
/// </summary>
public class QuestSystemDebugger : MonoBehaviour
{
    [Header("Debug Options")]
    public bool enableDebugLogs = true;
    public bool autoDebugOnStart = true;

    private void Start()
    {
        if (autoDebugOnStart)
        {
            // Wait a frame to ensure all systems are initialized
            Invoke(nameof(DebugQuestSystem), 0.5f);
        }
    }

    [ContextMenu("Debug Quest System")]
    public void DebugQuestSystem()
    {
        LogDebug("=== QUEST SYSTEM DEBUG ===");

        // Check QuestManager
        DebugQuestManager();

        // Check AdventurersGuild
        DebugAdventurersGuild();

        // Check Quest Assets
        DebugQuestAssets();

        LogDebug("=== DEBUG COMPLETE ===");
    }

    private void DebugQuestManager()
    {
        LogDebug("--- QuestManager ---");

        if (QuestManager.Instance == null)
        {
            LogDebug("❌ QuestManager.Instance is NULL!");
            return;
        }

        LogDebug($"✅ QuestManager found");
        LogDebug($"📊 Current Renown: {QuestManager.Instance.GetRenown()}");
        LogDebug($"📋 Active Quests: {QuestManager.Instance.GetActiveQuests().Count}");
        LogDebug($"🎯 Can Accept More: {QuestManager.Instance.CanAcceptMoreQuests()}");
    }

    private void DebugAdventurersGuild()
    {
        LogDebug("--- AdventurersGuild ---");

        var guild = FindFirstObjectByType<AdventurersGuild>();
        if (guild == null)
        {
            LogDebug("❌ AdventurersGuild component not found!");
            return;
        }

        LogDebug($"✅ AdventurersGuild found");

        var questBoard = guild.GetQuestBoard();
        LogDebug($"📋 Quest Board Count: {questBoard.Count}");

        if (questBoard.Count > 0)
        {
            LogDebug("📝 Quest Board Contents:");
            foreach (var quest in questBoard)
            {
                LogDebug($"  - {quest.questTitle} (Renown: {quest.minimumRenown}, Reward: {quest.goldReward}g)");
            }
        }
        else
        {
            LogDebug("⚠️ Quest Board is empty - calling RefreshQuestBoard()");
            guild.RefreshQuestBoard();

            var refreshedBoard = guild.GetQuestBoard();
            LogDebug($"📋 After refresh: {refreshedBoard.Count} quests");
        }
    }

    private void DebugQuestAssets()
    {
        LogDebug("--- Quest Assets ---");

        // Check Resources folder for quests
        var allQuests = Resources.LoadAll<Quest>("");
        LogDebug($"📚 Total Quest assets in Resources: {allQuests.Length}");

        if (allQuests.Length > 0)
        {
            LogDebug("📝 Available Quest Assets:");
            foreach (var quest in allQuests)
            {
                LogDebug($"  - {quest.questTitle} (Min Renown: {quest.minimumRenown}, File: {quest.name})");
            }
        }
        else
        {
            LogDebug("⚠️ No Quest assets found in Resources folder!");
        }

        // Check specific subfolders
        var questSubfolders = new string[] { "Quests", "Quests/Combat", "Quests/Rescue", "Quests/Retrieval", "Quests/Exploration" };

        foreach (var folder in questSubfolders)
        {
            var folderQuests = Resources.LoadAll<Quest>(folder);
            if (folderQuests.Length > 0)
            {
                LogDebug($"📁 {folder}: {folderQuests.Length} quests");
            }
        }
    }

    [ContextMenu("Create Test Quest")]
    public void CreateTestQuest()
    {
        LogDebug("Creating runtime test quest...");

        if (QuestManager.Instance == null)
        {
            LogDebug("❌ QuestManager not found!");
            return;
        }

        var testQuest = ScriptableObject.CreateInstance<Quest>();
        testQuest.questTitle = "Debug Test Quest";
        testQuest.questDescription = "A simple test quest for debugging the quest system.";
        testQuest.questType = QuestType.Combat;
        testQuest.difficulty = QuestDifficulty.Easy;
        testQuest.timeLimitDays = 7;
        testQuest.targetAreaName = "Test Area";
        testQuest.targetMapPosition = new Vector2Int(50, 50);
        testQuest.goldReward = 100;
        testQuest.renownReward = 10;
        testQuest.minimumRenown = 0; // Ensure it's available to new players

        testQuest.goals.Add(new QuestGoal
        {
            description = "Test objective",
            goalType = QuestGoalType.KillEnemies,
            targetName = "TestEnemy",
            targetCount = 1
        });

        bool accepted = QuestManager.Instance.AcceptQuest(testQuest);
        LogDebug($"Test quest acceptance: {(accepted ? "✅ SUCCESS" : "❌ FAILED")}");
    }

    [ContextMenu("Add Renown")]
    public void AddTestRenown()
    {
        if (QuestManager.Instance != null)
        {
            // Use reflection or debug method to add renown
            LogDebug("Adding test renown (this is a debug feature)");
            // In a real implementation, you'd need a way to modify renown for testing
        }
    }

    private void LogDebug(string message)
    {
        if (enableDebugLogs)
        {
            Debug.Log($"[QuestDebugger] {message}");
        }
    }
}
