from typing import Any, cast


def render_help_markdown(payload: dict[str, Any]) -> str:
    lines = [f"# {payload['name']}", ""]

    description = payload.get("description")
    if isinstance(description, str) and description:
        lines.extend([description, ""])

    usage = payload.get("usage")
    if isinstance(usage, str) and usage:
        lines.extend(["## Usage", "", "```text", usage, "```", ""])

    options = payload.get("options")
    if isinstance(options, list) and options:
        lines.extend(["## Options", ""])
        for raw_option in cast(list[Any], options):
            if not isinstance(raw_option, dict):
                continue
            lines.extend(_render_option(cast(dict[str, Any], raw_option)))
        lines.append("")

    commands = payload.get("commands")
    if isinstance(commands, list) and commands:
        lines.extend(["## Commands", ""])
        for raw_command in cast(list[Any], commands):
            if not isinstance(raw_command, dict):
                continue
            lines.extend(_render_command(cast(dict[str, Any], raw_command), depth=0))

    return "\n".join(lines).rstrip() + "\n"


def _render_option(option: dict[str, Any]) -> list[str]:
    return _render_option_with_indent(option, indent="")


def _render_option_with_indent(option: dict[str, Any], indent: str) -> list[str]:
    line = f"- `{option['name']}`"
    help_text = option.get("help")
    if isinstance(help_text, str) and help_text:
        line = f"{line}: {help_text}"

    details: list[str] = []
    envvar = option.get("envvar")
    if isinstance(envvar, str) and envvar:
        details.append(f"env: `{envvar}`")

    default = option.get("default")
    if default is not None:
        details.append(f"default: `{default}`")

    choices = option.get("choices")
    if isinstance(choices, list) and choices:
        rendered_choices = ", ".join(
            f"`{choice}`" for choice in cast(list[Any], choices)
        )
        details.append(f"choices: {rendered_choices}")

    if option.get("multiple") is True:
        details.append("multiple")

    if details:
        line = f"{line} ({'; '.join(details)})"

    return [f"{indent}{line}"]


def _render_command(command: dict[str, Any], depth: int) -> list[str]:
    indent = "  " * depth
    line = f"{indent}- `{command['name']}`"
    help_text = command.get("help")
    if isinstance(help_text, str) and help_text:
        line = f"{line}: {help_text}"

    lines = [line]

    nested_options = command.get("options")
    if isinstance(nested_options, list):
        option_indent = "  " * (depth + 2)
        for raw_option in cast(list[Any], nested_options):
            if isinstance(raw_option, dict):
                lines.extend(
                    _render_option_with_indent(
                        cast(dict[str, Any], raw_option), option_indent
                    )
                )

    nested_commands = command.get("commands")
    if isinstance(nested_commands, list):
        for raw_nested_command in cast(list[Any], nested_commands):
            if isinstance(raw_nested_command, dict):
                lines.extend(
                    _render_command(cast(dict[str, Any], raw_nested_command), depth + 1)
                )

    return lines
