using System.Text;
using AxCopilot.Models;

namespace AxCopilot.Services.Agent.SlashCommands;

/// <summary>Phase 22: /permissions — 권한 규칙 관리.</summary>
public class PermissionsCommand : ISlashCommand
{
    public string Name => "permissions";
    public string[] Aliases => new[] { "allowed-tools" };
    public string Description => "도구 허용/차단 규칙을 관리합니다";
    public string? ArgumentHint => "[mode <모드명>]";
    public bool RequiresActiveSession => false;

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

        if (!string.IsNullOrWhiteSpace(arguments))
        {
            var parts = arguments.Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
            if (parts[0].Equals("mode", StringComparison.OrdinalIgnoreCase) && parts.Length > 1)
            {
                var modeName = parts[1].Trim();
                if (Enum.TryParse<PermissionMode>(modeName, true, out _))
                {
                    llm.DefaultAgentPermission = modeName;
                    ctx.Settings.Save();
                    ctx.UpdateSessionHeader();
                    await ctx.SendSystemMessageAsync($"권한 모드가 **{modeName}**(으)로 변경되었습니다.");
                    return;
                }

                await ctx.SendSystemMessageAsync(
                    $"알 수 없는 모드: {modeName}\n사용 가능: Default, AcceptEdits, Plan, BypassPermissions");
                return;
            }
        }

        // 현재 상태 표시
        var sb = new StringBuilder("## 권한 설정\n");
        sb.AppendLine($"현재 모드: **{llm.DefaultAgentPermission}**\n");

        var allowRules = perms?.AllowRules ?? new List<PermissionRuleEntry>();
        var denyRules = perms?.DenyRules ?? new List<PermissionRuleEntry>();

        if (allowRules.Count > 0)
        {
            sb.AppendLine("### 허용 규칙");
            foreach (var r in allowRules)
                sb.AppendLine($"- {r.ToolName}({r.Pattern ?? "*"})");
        }

        if (denyRules.Count > 0)
        {
            sb.AppendLine("\n### 차단 규칙");
            foreach (var r in denyRules)
                sb.AppendLine($"- {r.ToolName}({r.Pattern ?? "*"})");
        }

        if (allowRules.Count == 0 && denyRules.Count == 0)
            sb.AppendLine("사용자 지정 규칙이 없습니다.");

        sb.AppendLine($"\n모드 변경: `/permissions mode <모드명>`");
        await ctx.SendSystemMessageAsync(sb.ToString());
    }
}
