# Familiar - Self-Hosted AI Companion Platform
# Copyright (c) 2026 George Scott Foley
# ORCID: 0009-0006-4957-0540
# Email: Georgescottfoley@proton.me
# Licensed under the MIT License - see LICENSE file for details

"""
Cross-channel formatting helpers.

Each channel uses a different markup syntax for bold, code, and italic text.
These helpers let the shared ConnectMixin build messages once and render them
correctly for any channel.
"""

from enum import Enum
from html import escape as _html_escape


class FormatMode(Enum):
    """Markup dialect understood by each channel."""

    HTML = "html"  # Telegram
    MARKDOWN = "markdown"  # Discord, Teams
    WHATSAPP = "whatsapp"  # WhatsApp (*bold*)
    PLAIN = "plain"  # Signal, Matrix


def fmt_bold(text: str, mode: FormatMode) -> str:
    """Render *text* as bold in the given format."""
    if mode is FormatMode.HTML:
        return f"<b>{text}</b>"
    if mode is FormatMode.MARKDOWN:
        return f"**{text}**"
    if mode is FormatMode.WHATSAPP:
        return f"*{text}*"
    return text


def fmt_code(text: str, mode: FormatMode) -> str:
    """Render *text* as inline code in the given format."""
    if mode is FormatMode.HTML:
        return f"<code>{_html_escape(text)}</code>"
    if mode in (FormatMode.MARKDOWN, FormatMode.WHATSAPP):
        return f"`{text}`"
    return text


def fmt_italic(text: str, mode: FormatMode) -> str:
    """Render *text* as italic in the given format."""
    if mode is FormatMode.HTML:
        return f"<i>{text}</i>"
    if mode is FormatMode.MARKDOWN:
        return f"*{text}*"
    if mode is FormatMode.WHATSAPP:
        return f"_{text}_"
    return text


def fmt_link(text: str, url: str, mode: FormatMode) -> str:
    """Render a clickable hyperlink in the given format."""
    if mode is FormatMode.HTML:
        return f'<a href="{url}" target="_blank" rel="noopener">{text}</a>'
    if mode in (FormatMode.MARKDOWN, FormatMode.WHATSAPP):
        return f"[{text}]({url})"
    return f"{text}: {url}"


def format_tool_results(tool_results, mode, max_results=5, max_output_len=80):
    """Format tool execution results as a brief summary."""
    if not tool_results:
        return ""
    lines = []
    shown = tool_results[:max_results]
    for tr in shown:
        name = str(getattr(tr, "tool_name", "unknown"))
        output = str(getattr(tr, "output", ""))
        if len(output) > max_output_len:
            output = output[:max_output_len] + "..."
        lines.append(f"  {fmt_code(name, mode)}: {output}")
    header = fmt_bold("Tool activity", mode)
    result = f"{header}\n" + "\n".join(lines)
    if len(tool_results) > max_results:
        result += f"\n  ... and {len(tool_results) - max_results} more"
    return result
