"""Markdown renderer for chat messages."""

from datetime import datetime

from rich.console import Group, RenderableType
from rich.markdown import Markdown
from rich.text import Text

from alloy_runtime_types.dtos.sessions import MessageResponse

from cli.tui.chat.renderers.base import (
    get_message_body,
)
from cli.tui.chat.types import extract_thinking_content, format_time

# Color for thinking/reasoning blocks
THINKING_COLOR = "#bb9af7"  # tokyo-night purple accent


class MarkdownRenderer:
    """Renders messages with Rich markdown formatting.

    Features:
        - User messages with muted styling
        - Assistant messages rendered as proper markdown (code blocks, headers, etc.)
        - Agent/model name in header
        - Timestamps on each message
        - Optimistic user message display
        - Waiting indicator while a response is in flight
        - Thinking/reasoning blocks with distinctive styling

    This is the default renderer for the chat interface. It uses Rich's Markdown
    class to properly render markdown syntax in assistant responses.
    """

    def render(
        self,
        messages: tuple[MessageResponse, ...],
        pending_user_message: str | None = None,
        assistant_name: str = "Assistant",
        is_generating: bool = False,
        thinking_collapsed: bool = False,
    ) -> Group:
        """Render messages to a Rich Group with proper markdown formatting.

        Args:
            messages: Tuple of message responses to render.
            pending_user_message: User message shown optimistically before server confirms.
            assistant_name: Name to display for assistant (agent name or model).
            is_generating: Whether currently waiting for the final response.
            thinking_collapsed: Whether thinking blocks should be collapsed.

        Returns:
            Rich Group containing formatted renderables suitable for display.
        """
        renderables: list[RenderableType] = []

        # Colors: user messages in dim/muted, assistant in accent color
        # Using colors that work well with tokyo-night theme
        user_color = "dim white"
        assistant_color = "#7aa2f7"  # tokyo-night blue accent

        for msg in messages:
            time_str = format_time(msg.created_at)

            if msg.role == "user":
                body = get_message_body(msg)
                header = Text(f"You [{time_str}]:", style=f"bold {user_color}")
                renderables.append(header)
                renderables.append(Text(body, overflow="fold"))
            else:
                body = get_message_body(msg)

                # For assistant messages, check for thinking content
                thinking_content = extract_thinking_content(msg)
                if thinking_content:
                    # Render any persisted thinking block using the collapse setting.
                    renderables.append(
                        self._render_thinking_block_renderable(
                            thinking_content,
                            collapsed=thinking_collapsed,
                        )
                    )
                    renderables.append(Text(""))

                header = Text(
                    f"{assistant_name} [{time_str}]:", style=f"bold {assistant_color}"
                )
                renderables.append(header)
                # Render assistant body as proper markdown
                renderables.append(Markdown(body))

            renderables.append(Text(""))

        # Show pending user message (optimistic UI)
        if pending_user_message:
            now_str = datetime.now().strftime("%H:%M")
            header = Text(f"You [{now_str}]:", style=f"bold {user_color}")
            renderables.append(header)
            renderables.append(Text(pending_user_message))
            renderables.append(Text(""))

        if is_generating:
            header = Text(f"{assistant_name}:", style=f"bold {assistant_color}")
            renderables.append(header)
            renderables.append(Text("Waiting for response...", style="dim"))

        return Group(*renderables)

    def _render_thinking_block_renderable(
        self,
        content: str,
        collapsed: bool = False,
    ) -> Text:
        """Render a thinking/reasoning block with distinctive styling.

        Args:
            content: The thinking content to render.
            collapsed: Whether to show collapsed view.

        Returns:
            Rich Text object for the thinking block.
        """
        if collapsed:
            # Show collapsed indicator with line count
            line_count = content.count("\n") + 1
            result = Text()
            result.append(f"◆ Thinking ({line_count} lines)...", style=THINKING_COLOR)
            result.append(" (expand with /thinking)", style="dim")
            return result

        # Full thinking block with border styling
        lines: list[str] = []
        lines.append("◆ Thinking")

        # Indent and dim the thinking content
        for line in content.split("\n"):
            lines.append(f"│ {line}")

        result = Text()
        result.append(lines[0] + "\n", style=f"bold {THINKING_COLOR}")
        for line in lines[1:]:
            result.append(line + "\n", style="dim italic")

        return result
