using System.Text;

namespace AxCopilot.Services.Agent.SlashCommands;

/// <summary>Phase 22: /mcp — MCP 서버 상태 확인.</summary>
public class McpSlashCommand : ISlashCommand
{
    public string Name => "mcp";
    public string[] Aliases => Array.Empty<string>();
    public string Description => "MCP 서버 상태를 확인합니다";
    public string? ArgumentHint => "[enable|disable <서버명>]";
    public bool RequiresActiveSession => false;

    public async Task ExecuteAsync(string arguments, IAgentChatContext ctx, CancellationToken ct)
    {
        var mcpServers = ctx.Settings.Settings.Llm.McpServers;

        if (string.IsNullOrWhiteSpace(arguments))
        {
            // 상태 표시
            if (mcpServers == null || mcpServers.Count == 0)
            {
                await ctx.SendSystemMessageAsync("등록된 MCP 서버가 없습니다.");
                return;
            }

            var sb = new StringBuilder("## MCP 서버 목록\n");
            foreach (var server in mcpServers)
            {
                var enabled = server.Enabled ? "활성" : "비활성";
                sb.AppendLine($"- **{server.Name}** [{enabled}] — `{server.Command}` {string.Join(" ", server.Args)}");
            }
            await ctx.SendSystemMessageAsync(sb.ToString());
            return;
        }

        var parts = arguments.Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
        var action = parts[0].ToLowerInvariant();
        var serverName = parts.Length > 1 ? parts[1] : null;

        if (mcpServers == null)
        {
            await ctx.SendSystemMessageAsync("등록된 MCP 서버가 없습니다.");
            return;
        }

        switch (action)
        {
            case "enable":
                ToggleServers(mcpServers, serverName, true);
                ctx.Settings.Save();
                await ctx.SendSystemMessageAsync($"MCP 서버 활성화: {serverName ?? "전체"}");
                break;

            case "disable":
                ToggleServers(mcpServers, serverName, false);
                ctx.Settings.Save();
                await ctx.SendSystemMessageAsync($"MCP 서버 비활성화: {serverName ?? "전체"}");
                break;

            default:
                await ctx.SendSystemMessageAsync("사용법: `/mcp [enable|disable] [서버명]`");
                break;
        }
    }

    private static void ToggleServers(List<Models.McpServerEntry> servers, string? name, bool enabled)
    {
        foreach (var s in servers)
        {
            if (name == null || s.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                s.Enabled = enabled;
        }
    }
}
