"""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 get_active_theme

from .base import ContentRenderer


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", "+++")

        lines = content.splitlines()
        highlighted = Text()
        for idx, line in enumerate(lines):
            if idx:
                highlighted.append("\n")
            if line.startswith("+") and not line.startswith("+++"):
                highlighted.append(line, style=theme.success.hex)
            elif line.startswith("-") and not line.startswith("---"):
                highlighted.append(line, style=theme.error.hex)
            elif line.startswith("@@"):
                highlighted.append(line, style=theme.text_dim.hex)
            else:
                highlighted.append(line, style=theme.text.hex)

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