using System;
using System.Collections.Generic;
using System.Linq;

namespace MosswartMassacre
{
    /// <summary>
    /// Dictionary-based /mm command dispatcher. Commands are registered with descriptions
    /// and routed by name lookup instead of a giant switch statement.
    /// </summary>
    internal class CommandRouter
    {
        private readonly Dictionary<string, (Action<string[]> handler, string description)> _commands
            = new Dictionary<string, (Action<string[]>, string)>(StringComparer.OrdinalIgnoreCase);

        /// <summary>
        /// Register a command with its handler and help description.
        /// </summary>
        internal void Register(string name, Action<string[]> handler, string description)
        {
            _commands[name] = (handler, description);
        }

        /// <summary>
        /// Dispatch a raw /mm command string. Returns false if the command was not found.
        /// </summary>
        internal bool Dispatch(string rawText)
        {
            string[] args = rawText.Substring(3).Trim().Split(' ');

            if (args.Length == 0 || string.IsNullOrEmpty(args[0]))
            {
                PluginCore.WriteToChat("Usage: /mm <command>. Try /mm help");
                return true;
            }

            string subCommand = args[0].ToLower();

            if (subCommand == "help")
            {
                PrintHelp();
                return true;
            }

            if (_commands.TryGetValue(subCommand, out var entry))
            {
                entry.handler(args);
                return true;
            }

            PluginCore.WriteToChat($"Unknown /mm command: {subCommand}. Try /mm help");
            return false;
        }

        private void PrintHelp()
        {
            PluginCore.WriteToChat("Mosswart Massacre Commands:");
            foreach (var kvp in _commands)
            {
                if (!string.IsNullOrEmpty(kvp.Value.description))
                {
                    PluginCore.WriteToChat($"/mm {kvp.Key,-18} - {kvp.Value.description}");
                }
            }
        }
    }
}
