using System.Text;

namespace AxCopilot.Services.Agent.SlashCommands;

/// <summary>Phase 22: /hooks — 활성 훅 설정 표시.</summary>
public class HooksCommand : ISlashCommand
{
    public string Name => "hooks";
    public string[] Aliases => Array.Empty<string>();
    public string Description => "활성화된 훅 설정을 표시합니다";
    public string? ArgumentHint => null;
    public bool RequiresActiveSession => false;

    public async Task ExecuteAsync(string arguments, IAgentChatContext ctx, CancellationToken ct)
    {
        var hooks = ctx.Hooks;
        if (hooks.Count == 0)
        {
            await ctx.SendSystemMessageAsync("활성 훅이 없습니다. 설정에서 훅을 추가할 수 있습니다.");
            return;
        }

        var sb = new StringBuilder("## 활성 훅\n");

        var groups = hooks.Where(h => h.Enabled).GroupBy(h => h.Event);
        foreach (var group in groups.OrderBy(g => g.Key.ToString()))
        {
            sb.AppendLine($"\n### {group.Key}");
            foreach (var hook in group)
            {
                var matcher = string.IsNullOrEmpty(hook.Matcher) ? "(전체)" : hook.Matcher;
                var target = hook.Mode switch
                {
                    HookExecutionMode.Command => $"`{hook.ScriptPath ?? hook.Arguments}`",
                    HookExecutionMode.Http => $"`{hook.Url}`",
                    HookExecutionMode.Prompt => $"LLM: `{Truncate(hook.Prompt, 50)}`",
                    HookExecutionMode.Agent => $"Agent: `{Truncate(hook.Prompt, 50)}`",
                    _ => "(알 수 없음)",
                };
                var flags = new List<string>();
                if (hook.Once) flags.Add("once");
                if (hook.IsAsync) flags.Add("async");
                var flagStr = flags.Count > 0 ? $" [{string.Join(", ", flags)}]" : "";

                sb.AppendLine($"- [{hook.Mode}] {matcher} → {target}{flagStr}");
            }
        }

        await ctx.SendSystemMessageAsync(sb.ToString());
    }

    private static string Truncate(string? text, int max)
    {
        if (string.IsNullOrEmpty(text)) return "";
        return text.Length <= max ? text : text[..max] + "...";
    }
}
