"""
测试 web_tools.py — HTML 清洗、JS 重定向检测、fetch_url 改造
"""
import sys
from pathlib import Path

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

from aacode.tools.web_tools import WebTools


class MockSafetyGuard:
    def check(self, *args, **kwargs):
        return True


class TestCleanHTML:
    """Fix 1a: _clean_html()"""

    def test_strips_script_tags(self):
        html = "<html><head><script>console.log('hi')</script></head><body>Hello</body></html>"
        result = WebTools._clean_html(html)
        assert "console.log" not in result
        assert "Hello" in result

    def test_strips_style_tags(self):
        html = "<html><head><style>.a{color:red}</style></head><body>Content</body></html>"
        result = WebTools._clean_html(html)
        assert ".a{color:red}" not in result
        assert "Content" in result

    def test_strips_head_section(self):
        html = "<html><head><meta charset='utf-8'><title>T</title></head><body>Body text</body></html>"
        result = WebTools._clean_html(html)
        assert "Body text" in result

    def test_pytorch_style_page(self):
        """模拟 PyTorch 文档：head 中有大量 CSS link，body 在 ~14700 字节后"""
        head_boilerplate = (
            "<!DOCTYPE html>\n<html lang='en'>\n<head>\n"
            + "\n".join([f'<link href="css_{i}.css" rel="stylesheet"/>' for i in range(200)])
            + "\n<script data-cfasync='false'>document.documentElement.dataset.mode = localStorage.getItem('mode');</script>"
            + "\n" + "\n".join([f'<script src="js_{i}.js"></script>' for i in range(50)])
            + "\n</head>\n<body>\n"
        )
        body_content = (
            "<h1>PyTorch 2.12 documentation</h1>\n"
            "<p>torch.Tensor is the central class. torch.is_tensor, torch.is_floating_point.</p>\n"
            "<h2>Autograd mechanics</h2>\n"
            "<p>Excluding subgraphs from backward. torch.autograd.backward.</p>\n"
            "<h2>torch.nn</h2>\n"
            "<p>Containers, Convolution Layers, Pooling layers.</p>\n"
            "</body></html>"
        )
        html = head_boilerplate + body_content

        result = WebTools._clean_html(html)

        assert "PyTorch 2.12 documentation" in result
        assert "torch.Tensor" in result
        assert "Autograd mechanics" in result
        assert "torch.nn" in result
        assert "getItem" not in result  # JS code removed
        assert "css_" not in result  # CSS removed
        assert "localStorage" not in result

    def test_empty_html(self):
        assert WebTools._clean_html("") == ""

    def test_no_tags(self):
        assert WebTools._clean_html("Plain text") == "Plain text"

    def test_html_entities_decoded(self):
        html = "<p>&amp; &lt; &gt; &quot;</p>"
        result = WebTools._clean_html(html)
        assert "&" in result
        assert "<" in result
        assert ">" in result
        assert '"' in result


class TestDetectJSRedirect:
    """Fix 1b: _detect_js_redirect()"""

    def test_location_replace(self):
        html = '<script>location.replace("../../2.12/notes/autograd.html");</script>'
        url = "https://pytorch.org/docs/stable/notes/autograd.html"
        result = WebTools._detect_js_redirect(html, url)
        assert result == "https://pytorch.org/docs/2.12/notes/autograd.html"

    def test_location_href(self):
        html = '<script>location.href="/new-page"</script>'
        url = "https://example.com"
        result = WebTools._detect_js_redirect(html, url)
        assert result == "https://example.com/new-page"

    def test_meta_refresh(self):
        html = '<meta http-equiv="refresh" content="0; url=../2.12/nn.html">'
        url = "https://pytorch.org/docs/2.11/nn.html"
        result = WebTools._detect_js_redirect(html, url)
        assert result == "https://pytorch.org/docs/2.12/nn.html"

    def test_no_redirect(self):
        html = "<html><body><h1>Normal Page</h1></body></html>"
        result = WebTools._detect_js_redirect(html, "https://example.com")
        assert result is None

    def test_absolute_redirect_url(self):
        html = '<script>location.replace("https://other.com/page")</script>'
        result = WebTools._detect_js_redirect(html, "https://example.com")
        assert result == "https://other.com/page"


class TestFetchURLWithCleanHTML:
    """集成测试：fetch_url 在截断前清洗 HTML"""

    @staticmethod
    def _make_result_dict(**overrides) -> dict:
        base = {
            "success": True,
            "url": "",
            "status_code": 200,
            "content_type": "text/html",
            "content_length": 0,
            "content": "",
        }
        base.update(overrides)
        return base


if __name__ == "__main__":
    print("=== TestCleanHTML ===")
    t = TestCleanHTML()
    for name in dir(t):
        if name.startswith("test_"):
            try:
                getattr(t, name)()
                print(f"  {name}: PASS")
            except AssertionError as e:
                print(f"  {name}: FAIL - {e}")

    print("\n=== TestDetectJSRedirect ===")
    t = TestDetectJSRedirect()
    for name in dir(t):
        if name.startswith("test_"):
            try:
                getattr(t, name)()
                print(f"  {name}: PASS")
            except AssertionError as e:
                print(f"  {name}: FAIL - {e}")
