namespace AxCopilot.Services.Agent.SlashCommands;

/// <summary>
/// Phase 22: 사용자 입력 라우터.
/// 슬래시 명령 → 스킬 → 일반 메시지 순으로 라우팅합니다.
/// </summary>
public class InputRouter
{
    private readonly SlashCommandRegistry _slashCommands;

    public InputRouter(SlashCommandRegistry slashCommands)
    {
        _slashCommands = slashCommands;
    }

    /// <summary>사용자 입력을 분석하여 라우팅 결과를 반환합니다.</summary>
    public InputRouteResult Route(string input)
    {
        if (string.IsNullOrWhiteSpace(input))
            return InputRouteResult.Message(input);

        if (!input.StartsWith('/'))
            return InputRouteResult.Message(input);

        var spaceIdx = input.IndexOf(' ');
        var commandPart = spaceIdx > 0 ? input[..spaceIdx] : input;
        var argsPart = spaceIdx > 0 ? input[(spaceIdx + 1)..] : "";

        // 1. 내장 슬래시 명령 확인
        var cmd = _slashCommands.Resolve(commandPart);
        if (cmd != null)
            return InputRouteResult.SlashCommand(cmd, argsPart);

        // 2. 스킬 검색
        var skillName = commandPart.TrimStart('/');
        var skill = SkillService.Find(skillName);
        if (skill != null)
            return InputRouteResult.Skill(skill, argsPart);

        // 3. 미인식 → 일반 메시지로 전달
        return InputRouteResult.Message(input);
    }
}

/// <summary>입력 라우팅 결과.</summary>
public class InputRouteResult
{
    public InputRouteType Type { get; init; }
    public string? MessageText { get; init; }
    public ISlashCommand? Command { get; init; }
    public string CommandArgs { get; init; } = "";
    public SkillDefinition? SkillDef { get; init; }

    public static InputRouteResult Message(string text) =>
        new() { Type = InputRouteType.Message, MessageText = text };

    public static InputRouteResult SlashCommand(ISlashCommand cmd, string args) =>
        new() { Type = InputRouteType.SlashCommand, Command = cmd, CommandArgs = args };

    public static InputRouteResult Skill(SkillDefinition skill, string args) =>
        new() { Type = InputRouteType.Skill, SkillDef = skill, CommandArgs = args };
}

/// <summary>입력 라우팅 유형.</summary>
public enum InputRouteType
{
    /// <summary>일반 메시지 → LLM으로 전달.</summary>
    Message,
    /// <summary>내장 슬래시 명령 → 즉시 실행.</summary>
    SlashCommand,
    /// <summary>스킬 명령 → 스킬 실행.</summary>
    Skill,
}
