"""Tests for WhatsApp response formatting helpers."""

from app.agents.whatsapp_formatter import (
    FormattedResponse,
    detect_options,
    format_for_whatsapp,
    strip_markdown,
)


class TestStripMarkdown:
    def test_strip_markdown_headers(self):
        text = "# Title\n## Header\nBody text"

        assert strip_markdown(text) == "Title\nHeader\nBody text"

    def test_strip_markdown_bold(self):
        text = "This is **bold** text"

        assert strip_markdown(text) == "This is bold text"

    def test_strip_markdown_italic(self):
        text = "This is *italic* text"

        assert strip_markdown(text) == "This is italic text"

    def test_strip_markdown_code_blocks(self):
        text = "Before\n```python\nprint('hi')\n```\nAfter"

        assert strip_markdown(text) == "Before\n\nAfter"

    def test_strip_markdown_inline_code(self):
        text = "Use `code` here"

        assert strip_markdown(text) == "Use code here"

    def test_strip_markdown_links(self):
        text = "Read [the docs](https://example.com/docs) first"

        assert strip_markdown(text) == "Read the docs first"


class TestFormatForWhatsApp:
    def test_format_for_whatsapp_basic(self):
        result = format_for_whatsapp("Hello from WhatsApp")

        assert result == FormattedResponse(
            text="Hello from WhatsApp",
            options=None,
            was_truncated=False,
        )

    def test_format_for_whatsapp_truncation(self):
        text = "a" * 5000

        result = format_for_whatsapp(text)

        assert len(result.text) == 4096
        assert result.text == ("a" * 4093) + "..."

    def test_format_for_whatsapp_was_truncated_flag(self):
        text = "b" * 5000

        result = format_for_whatsapp(text)

        assert result.was_truncated is True

    def test_format_preserves_plain_text(self):
        text = "Plain text without markdown or numbering."

        result = format_for_whatsapp(text)

        assert result.text == text
        assert result.options is None
        assert result.was_truncated is False


class TestDetectOptions:
    def test_detect_options_numbered_list(self):
        text = "1. First option\n2. Second option\n3. Third option"

        assert detect_options(text) == ["First option", "Second option", "Third option"]

    def test_detect_options_too_few(self):
        text = "1. Only option"

        assert detect_options(text) is None

    def test_detect_options_too_many(self):
        text = "\n".join(f"{index}. Option {index}" for index in range(1, 12))

        assert detect_options(text) is None

    def test_detect_options_parenthesis_format(self):
        text = "1) Starter\n2) Main\n3) Dessert"

        assert detect_options(text) == ["Starter", "Main", "Dessert"]
