"""
测试 react_loop.py — _format_observation_for_display() fetch_url 显示摘要
"""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).parent.parent))

from aacode.core.react_loop import AsyncReActLoop, ActionItem


class MockContextManager:
    async def get_context(self):
        return ""


def test_fetch_url_display_summary():
    """fetch_url 结果显示为摘要，不渲染原始 HTML"""
    result = {
        "success": True,
        "url": "https://pytorch.org/docs/nn.html",
        "status_code": 200,
        "content_type": "text/html",
        "content_length": 4500,
        "raw_length": 15000,
        "content": (
            "PyTorch 2.12 documentation Shortcuts Tutorials Docs..."
            + "torch.Tensor is the central class is_tensor is_floating_point..."
            + "Autograd mechanics Excluding subgraphs from backward..."
            + "torch.nn Containers Convolution Layers Pooling layers..."
        ),
    }

    loop = AsyncReActLoop(
        model_caller=lambda x: None,
        tools={},
        context_manager=MockContextManager(),
        max_iterations=50,
        project_path=Path("/tmp"),
    )

    display = loop._format_observation_for_display("fetch_url", result)

    # 应该包含 URL
    assert "pytorch.org/docs/nn.html" in display
    # 应显示原始字节数和清洗后字符数
    assert "15000" in display
    assert "4500" in display
    # 应包含内容预览
    assert "Autograd mechanics" in display
    # 应有提示
    assert "run_shell" in display
    # 不应有原始 HTML 标签
    assert "<html>" not in display or "<!DOCTYPE" not in display

    print("  test_fetch_url_display_summary: PASS")


def test_fetch_url_with_warning():
    """fetch_url 结果有 content_warning 时展示警告"""
    result = {
        "success": True,
        "url": "https://spa-site.com",
        "status_code": 200,
        "content_type": "text/html",
        "content_length": 20,
        "raw_length": 3000,
        "content_warning": "[WARNING: This page appears to be dynamically rendered (SPA).]",
        "content": "Loading...",
    }

    loop = AsyncReActLoop(
        model_caller=lambda x: None,
        tools={},
        context_manager=MockContextManager(),
        max_iterations=50,
        project_path=Path("/tmp"),
    )

    display = loop._format_observation_for_display("fetch_url", result)

    assert "SPA" in display
    assert "dynamically rendered" in display
    print("  test_fetch_url_with_warning: PASS")


def test_non_fetch_url_not_affected():
    """非 fetch_url 的结果不受影响"""
    loop = AsyncReActLoop(
        model_caller=lambda x: None,
        tools={},
        context_manager=MockContextManager(),
        max_iterations=50,
        project_path=Path("/tmp"),
    )

    result = {"returncode": 0, "stdout": "hello world"}
    display = loop._format_observation_for_display("run_shell", result)

    assert "hello world" in display
    assert "🌐" not in display
    print("  test_non_fetch_url_not_affected: PASS")


if __name__ == "__main__":
    test_fetch_url_display_summary()
    test_fetch_url_with_warning()
    test_non_fetch_url_not_affected()
