"""Typer utils."""

import re

from typer.core import TyperGroup


class AliasGroup(TyperGroup):
    """Add support for command aliases to Typer.

    Extends https://github.com/fastapi/typer/issues/132#issuecomment-2417492805
    Hopefully one day obsolete if this gets added: https://github.com/fastapi/typer/issues/1242
    """

    _hidden_aliases = {}

    @classmethod
    def register_hidden_alias(cls, command, hidden_alias: str):  # noqa D102
        """Very ugly way to add support for aliases.

        TODO: replace with something better, or wait until typer has something built in.
        """
        cls._hidden_aliases.setdefault(command, []).append(hidden_alias)

    def _unalias(self, command):
        for cmd, aliases in self._hidden_aliases.items():
            if command in aliases:
                return cmd
        return command

    _CMD_SPLIT_P = re.compile(r" ?[,|] ?")

    def get_command(self, ctx, cmd_name):  # noqa D102
        cmd_name = self._group_cmd_name(self._unalias(cmd_name))
        return super().get_command(ctx, cmd_name)

    def _group_cmd_name(self, default_name):
        for cmd in self.commands.values():
            name = cmd.name
            if name and default_name in self._CMD_SPLIT_P.split(name):
                return name
        return default_name
