"""WhatsApp response formatter.

Strips markdown, truncates to WhatsApp limits, and detects structured
option lists that could be rendered as interactive messages.
"""

import re
from dataclasses import dataclass

MAX_TEXT_LENGTH = 4096


@dataclass
class FormattedResponse:
    """Result of formatting an agent response for WhatsApp."""

    text: str
    # If the response contains a numbered option list, these are extracted
    # for potential interactive message rendering.
    options: list[str] | None = None
    # Whether the response was truncated to fit WhatsApp limits.
    was_truncated: bool = False


def format_for_whatsapp(text: str) -> FormattedResponse:
    """Format an agent response for WhatsApp delivery.

    Strips markdown, truncates to 4096 chars, and detects numbered
    option lists for interactive message rendering.
    """
    cleaned = strip_markdown(text)
    options = detect_options(cleaned)
    truncated = False
    if len(cleaned) > MAX_TEXT_LENGTH:
        cleaned = cleaned[: MAX_TEXT_LENGTH - 3] + "..."
        truncated = True
    return FormattedResponse(text=cleaned, options=options, was_truncated=truncated)


def strip_markdown(text: str) -> str:
    """Remove markdown formatting that WhatsApp cannot render."""
    # Remove headers (## Header)
    text = re.sub(r"^#{1,6}\s+", "", text, flags=re.MULTILINE)
    # Remove bold (**text** or __text__)
    text = re.sub(r"\*\*(.+?)\*\*", r"\1", text)
    text = re.sub(r"__(.+?)__", r"\1", text)
    # Remove italic (*text* or _text_) — careful not to strip underscores in words
    text = re.sub(r"(?<!\w)\*(.+?)\*(?!\w)", r"\1", text)
    text = re.sub(r"(?<!\w)_(.+?)_(?!\w)", r"\1", text)
    # Remove code blocks (```...```)
    text = re.sub(r"```[\s\S]*?```", "", text)
    # Remove inline code (`code`)
    text = re.sub(r"`(.+?)`", r"\1", text)
    # Remove link syntax [text](url) -> text
    text = re.sub(r"\[(.+?)\]\(.+?\)", r"\1", text)
    # Remove image syntax ![alt](url)
    text = re.sub(r"!\[.*?\]\(.+?\)", "", text)
    # Remove horizontal rules
    text = re.sub(r"^[-*_]{3,}$", "", text, flags=re.MULTILINE)
    # Collapse multiple blank lines
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()


def detect_options(text: str) -> list[str] | None:
    """Detect numbered option lists in the response text.

    Returns extracted options if a clear numbered list is found,
    suitable for WhatsApp interactive list/button rendering.
    Returns None if no clear option list is detected.
    """
    # Match lines like "1. Option text" or "1) Option text"
    pattern = r"^\s*\d+[.)\s]+(.+)$"
    matches = re.findall(pattern, text, re.MULTILINE)
    # Only return if we have 2-10 options (WhatsApp interactive limits)
    if 2 <= len(matches) <= 10:
        return [match.strip() for match in matches]
    return None
