"""Output formatting and display."""

import sys

from rich.console import Console, Group
from rich.panel import Panel
from rich.markdown import Markdown
from rich.text import Text


def _ensure_utf8(stream) -> None:
    """Reconfigure a stream to UTF-8 if it isn't already.

    On Windows the default encoding is often cp1252, which crashes on the
    Unicode characters in bridge art and status symbols.  Calling
    reconfigure() on the existing stream is safe and preserves Rich's
    terminal/color detection (unlike wrapping in a new TextIOWrapper).
    """
    if (
        hasattr(stream, "reconfigure")
        and hasattr(stream, "encoding")
        and stream.encoding
        and stream.encoding.lower().replace("-", "") != "utf8"
    ):
        stream.reconfigure(encoding="utf-8")


def make_console(*, stderr: bool = False) -> Console:
    """Create a Console that outputs UTF-8 even on Windows (cp1252)."""
    _ensure_utf8(sys.stderr if stderr else sys.stdout)
    return Console(stderr=stderr)


console = make_console()


def success(message: str) -> None:
    """Display success message."""
    console.print(f"[green]✓[/green] {message}")


def error(message: str) -> None:
    """Display error message."""
    console.print(f"[red]✗[/red] {message}")


def warning(message: str) -> None:
    """Display warning message."""
    console.print(f"[yellow]![/yellow] {message}")


def info(message: str) -> None:
    """Display info message."""
    console.print(f"[blue]i[/blue] {message}")


def panel(content: str, title: str | None = None) -> None:
    """Display content in a panel."""
    console.print(Panel(content, title=title))


BRIDGE_ART = (
    "      [bold]▄▄▄▄▄▄▄[/bold]\n"
    "    [bold]▄▀[/bold]  [purple]▴[/purple]    [bold]▀▄[/bold]\n"
    "   [bold]██[/bold]  [purple]✦✦✦[/purple]    [bold]██[/bold]\n"
    "   [bold]██[/bold]   [purple]▾[/purple]  [blue]▴[/blue]  [bold]██[/bold]\n"
    "   [bold]██[/bold]     [blue]✧✧✧[/blue] [bold]██[/bold]\n"
    "   [bold]██[/bold]      [blue]▾[/blue]  [bold]██[/bold]\n"
    "   [bold]▀▀[/bold]         [bold]▀▀[/bold]"
)


def bridge_banner(target: Console | None = None) -> None:
    """Print the gjalla bridge ASCII art."""
    c = target or console
    c.print()
    c.print(Text.from_markup(BRIDGE_ART))
    c.print()


def _strip_first_heading(content: str) -> str:
    """Remove the first h1 heading if present (avoids duplicate with panel title)."""
    import re
    return re.sub(r"^# [^\n]*\n+", "", content.lstrip(), count=1)


def section_display(
    title: str,
    content: str,
    color: str = "purple",
    is_markdown: bool = True,
    markup: bool = False,
) -> None:
    """Display content in a panel with bridge art and title.

    Args:
        is_markdown: Render content as markdown.
        markup: Render Rich markup tags in plain-text content (ignored when is_markdown=True).
    """
    bridge = Text.from_markup(BRIDGE_ART)
    if is_markdown:
        content = _strip_first_heading(content)
        body = Markdown(content)
    elif markup:
        body = Text.from_markup(content)
    else:
        body = Text(content)
    console.print()
    console.print(Panel(
        Group(bridge, Text(), body),
        title=f"[{color} bold]{title}[/{color} bold]",
        title_align="left",
        padding=(1, 2),
    ))


def markdown(content: str) -> None:
    """Display markdown content."""
    console.print(Markdown(content))
