"""验证 Markdown 降级为纯文本时的反转义逻辑。"""

from __future__ import annotations

import pytest
from aiogram.exceptions import TelegramBadRequest
from aiogram.methods.base import TelegramMethod

import bot


@pytest.mark.asyncio()
async def test_markdown_guard_plain_fallback_removes_escapes() -> None:
    """确保回退纯文本时不会残留 MarkdownV2 转义反斜杠。"""

    delivered: list[str] = []

    class _DummyMethod(TelegramMethod):
        """构造最小化的 TelegramMethod 以便创建异常对象。"""

        __returning__ = bool

        @property
        def __api_method__(self) -> str:
            return "testMethod"

        def build_response(self, data, bot):  # pragma: no cover - 测试不会触发
            return True

        def build_request(self, bot):  # pragma: no cover - 测试不会触发
            return "testMethod", {}

    async def _failing_sender(_: str) -> None:
        raise TelegramBadRequest(_DummyMethod(), "Bad Request: can't parse entities")

    async def _raw_sender(payload: str) -> None:
        delivered.append(payload)

    original = "测试 \\_Markdown\\_ 转义"
    result = await bot._send_with_markdown_guard(original, _failing_sender, raw_sender=_raw_sender)

    assert delivered and delivered[0] == "测试 _Markdown_ 转义"
    assert result == "测试 _Markdown_ 转义"
