"""Renderer for unified diff messages."""

from __future__ import annotations

from rich.console import RenderableType
from rich.panel import Panel
from rich.text import Text

from clients.terminal.tui.themes import Theme, get_active_theme

from .base import ContentRenderer


def highlight_unified_diff(text: str, theme: Theme) -> Text:
    """Color a unified-diff string: ``+`` green, ``-`` red, ``@@`` dim, rest text.

    Shared by the standalone ``diff`` event renderer and the ``filesystem``
    tool-call renderer (``edit_lines`` / ``smart_edit`` / ``diff`` actions embed
    a unified diff as plain text in ``ToolResult.output``).
    """
    out = Text()
    for idx, line in enumerate(text.splitlines()):
        if idx:
            out.append("\n")
        if line.startswith("+") and not line.startswith("+++"):
            out.append(line, style=theme.success.hex)
        elif line.startswith("-") and not line.startswith("---"):
            out.append(line, style=theme.error.hex)
        elif line.startswith("@@"):
            out.append(line, style=theme.text_dim.hex)
        else:
            out.append(line, style=theme.text.hex)
    return out


class DiffRenderer(ContentRenderer):
    """Render a unified diff with added/removed line highlighting."""

    def accepts(self, msg: dict) -> bool:
        return msg.get("type") == "diff"

    def render(self, msg: dict) -> RenderableType:
        theme = get_active_theme()
        content = msg.get("content", "")
        old_label = msg.get("old_label", "---")
        new_label = msg.get("new_label", "+++")

        highlighted = highlight_unified_diff(content, theme)

        return Panel(
            highlighted,
            title=f"diff: {old_label} → {new_label}",
            title_align="left",
            border_style=theme.border.hex,
        )