from __future__ import annotations

from flow_xhs.cli.spec.model import CliSpec, CommandSpec
from flow_xhs.cli.spec.render_help import render_command_help, render_group_help, render_root_help, render_topic_help
from flow_xhs.cli.spec.views import get_group_view, list_root_entries


def render_cli_markdown(spec: CliSpec) -> str:
    parts: list[str] = [
        f"# {spec.cli_name}",
        "",
        "## Root Help",
        "",
        "```text",
        render_root_help(spec),
        "```",
    ]
    if spec.topics:
        parts.extend(["", "## Reference Notes"])
        for topic in spec.topics:
            parts.extend(
                [
                    "",
                    f"### `{topic.id}`",
                    "",
                    "```text",
                    render_topic_help(topic),
                    "```",
                ]
            )
    seen_groups: set[tuple[str, ...]] = set()
    for entry in list_root_entries(spec):
        if entry.kind != "group":
            continue
        group = get_group_view(spec, entry.path)
        if group is None or group.path in seen_groups:
            continue
        seen_groups.add(group.path)
        parts.extend(
            [
                "",
                f"## `{group.display_path}`",
                "",
                "```text",
                render_group_help(group),
                "```",
            ]
        )
    for command in spec.commands:
        parts.extend(
            [
                "",
                f"## `{command.display_path}`",
                "",
                "```text",
                render_command_help(spec, command),
                "```",
            ]
        )
    return "\n".join(parts)


def render_command_markdown(spec: CliSpec, command: CommandSpec) -> str:
    return "\n".join(
        [
            f"# `{command.display_path}`",
            "",
            "```text",
            render_command_help(spec, command),
            "```",
        ]
    )
