using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Mag.Shared.Spells;

namespace MosswartMassacre
{
    /// <summary>
    /// Manages spell identification and cantrip detection for the Flag Tracker
    /// </summary>
    public static class SpellManager
    {
        private static readonly Dictionary<int, Spell> SpellsById = new Dictionary<int, Spell>();
        private static readonly List<string[]> SpellData = new List<string[]>();
        private static bool isInitialized = false;

        static SpellManager()
        {
            Initialize();
        }

        private static void Initialize()
        {
            if (isInitialized) return;

            try
            {
                // Load spell data from embedded CSV resource
                var assembly = Assembly.GetExecutingAssembly();
                
                // Try to find the resource with different naming patterns
                var availableResources = assembly.GetManifestResourceNames();
                var spellResource = availableResources.FirstOrDefault(r => r.Contains("Spells.csv"));
                
                if (string.IsNullOrEmpty(spellResource))
                {
                    // If not embedded, try to load from file system
                    var csvPath = Path.Combine(Path.GetDirectoryName(assembly.Location), "..", "Shared", "Spells", "Spells.csv");
                    if (File.Exists(csvPath))
                    {
                        LoadFromFile(csvPath);
                        isInitialized = true;
                        return;
                    }
                }
                else
                {
                    using (var stream = assembly.GetManifestResourceStream(spellResource))
                    {
                        if (stream != null)
                        {
                            using (var reader = new StreamReader(stream))
                            {
                                LoadFromReader(reader);
                            }
                        }
                    }
                }

                isInitialized = true;
            }
            catch (Exception ex)
            {
                PluginCore.WriteToChat($"SpellManager initialization error: {ex.Message}");
            }
        }

        private static void LoadFromFile(string path)
        {
            using (var reader = new StreamReader(path))
            {
                LoadFromReader(reader);
            }
        }

        private static void LoadFromReader(StreamReader reader)
        {
            // Skip header line
            var header = reader.ReadLine();
            
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                if (!string.IsNullOrWhiteSpace(line))
                {
                    var parts = line.Split(',');
                    if (parts.Length >= 6) // Minimum required fields
                    {
                        SpellData.Add(parts);
                        
                        // Parse spell data
                        if (int.TryParse(parts[0], out int id))
                        {
                            var name = parts[1];
                            int.TryParse(parts[3], out int difficulty);
                            int.TryParse(parts[4], out int duration);
                            int.TryParse(parts[5], out int family);
                            
                            var spell = new Spell(id, name, difficulty, duration, family);
                            SpellsById[id] = spell;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Gets a spell by its ID
        /// </summary>
        public static Spell GetSpell(int id)
        {
            if (SpellsById.TryGetValue(id, out var spell))
                return spell;
            return null;
        }

        /// <summary>
        /// Gets a spell by its name (case-insensitive)
        /// </summary>
        public static Spell GetSpell(string name)
        {
            return SpellsById.Values.FirstOrDefault(s => 
                string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// Gets the total number of spells loaded
        /// </summary>
        public static int GetSpellCount()
        {
            return SpellsById.Count;
        }

        /// <summary>
        /// Detects if a spell is a cantrip and returns its info
        /// </summary>
        public static CantripInfo DetectCantrip(Spell spell)
        {
            if (spell == null || spell.CantripLevel == Spell.CantripLevels.None)
                return null;

            var info = new CantripInfo
            {
                SpellId = spell.Id,
                Name = spell.Name,
                Level = GetCantripLevelName(spell.CantripLevel),
                Color = GetCantripColor(spell.CantripLevel)
            };

            // Extract skill/attribute name from spell name
            info.SkillName = ExtractSkillFromSpellName(spell.Name, info.Level);
            
            return info;
        }

        private static string GetCantripLevelName(Spell.CantripLevels level)
        {
            switch (level)
            {
                case Spell.CantripLevels.Minor: return "Minor";
                case Spell.CantripLevels.Moderate: return "Moderate";
                case Spell.CantripLevels.Major: return "Major";
                case Spell.CantripLevels.Epic: return "Epic";
                case Spell.CantripLevels.Legendary: return "Legendary";
                default: return "N/A";
            }
        }

        private static System.Drawing.Color GetCantripColor(Spell.CantripLevels level)
        {
            switch (level)
            {
                case Spell.CantripLevels.Minor: return System.Drawing.Color.White;
                case Spell.CantripLevels.Moderate: return System.Drawing.Color.Green;
                case Spell.CantripLevels.Major: return System.Drawing.Color.Blue;
                case Spell.CantripLevels.Epic: return System.Drawing.Color.Purple;
                case Spell.CantripLevels.Legendary: return System.Drawing.Color.Orange;
                default: return System.Drawing.Color.White;
            }
        }

        private static string ExtractSkillFromSpellName(string spellName, string level)
        {
            // Remove the cantrip level prefix
            var skillPart = spellName;
            if (!string.IsNullOrEmpty(level) && skillPart.StartsWith(level + " "))
            {
                skillPart = skillPart.Substring(level.Length + 1);
            }

            // Map common spell name patterns to skill names
            if (skillPart.Contains("Strength")) return "Strength";
            if (skillPart.Contains("Endurance")) return "Endurance";
            if (skillPart.Contains("Coordination")) return "Coordination";
            if (skillPart.Contains("Quickness")) return "Quickness";
            if (skillPart.Contains("Focus")) return "Focus";
            if (skillPart.Contains("Self") || skillPart.Contains("Willpower")) return "Willpower";
            
            // Protection mappings
            if (skillPart.Contains("Armor")) return "Armor";
            if (skillPart.Contains("Bludgeoning")) return "Bludgeoning Ward";
            if (skillPart.Contains("Piercing")) return "Piercing Ward";
            if (skillPart.Contains("Slashing")) return "Slashing Ward";
            if (skillPart.Contains("Flame") || skillPart.Contains("Fire")) return "Flame Ward";
            if (skillPart.Contains("Frost") || skillPart.Contains("Cold")) return "Frost Ward";
            if (skillPart.Contains("Acid")) return "Acid Ward";
            if (skillPart.Contains("Lightning") || skillPart.Contains("Electric")) return "Storm Ward";
            
            // Return the skill part as-is if no mapping found
            return skillPart;
        }

        /// <summary>
        /// Information about a detected cantrip
        /// </summary>
        public class CantripInfo
        {
            public int SpellId { get; set; }
            public string Name { get; set; }
            public string SkillName { get; set; }
            public string Level { get; set; }
            public System.Drawing.Color Color { get; set; }
        }
    }
}