"""
完整的测试套件示例
涵盖常用测试场景
"""
import pytest
import asyncio
from pathlib import Path

# 导入playwright-ez
import sys
sys.path.insert(0, "/root/.openclaw/workspace/projects/playwright-ez/src")
from playwright_ez import (
    EasyBrowser,
    Config,
    WaitCondition,
    SmartSelector,
    FormHandler,
    DataExtractor,
    VisualTester,
    NetworkMonitor,
    PerformanceAnalyzer,
    Debugger,
    ErrorHandler,
    AssertionHelper,
    DeviceEmulator,
    AntiDetection,
    fake_user,
    fake_email,
    fake_name,
)


class TestBrowserBasics:
    """浏览器基础功能测试"""

    @pytest.fixture
    async def browser(self):
        """浏览器fixture"""
        config = Config(headless=True, log_level="INFO")
        browser = EasyBrowser(config)
        await browser.start()
        yield browser
        await browser.close()

    @pytest.mark.asyncio
    async def test_navigation(self, browser):
        """测试页面导航"""
        await browser.goto("https://www.baidu.com")

        title = await browser.page.title()
        assert "百度" in title

        url = browser.page.url
        assert "baidu.com" in url

    @pytest.mark.asyncio
    async def test_element_operations(self, browser):
        """测试元素操作"""
        await browser.goto("https://www.baidu.com")

        # 获取文本
        text = await browser.get_text("#su")  # 百度一下按钮
        assert text is not None

        # 点击链接
        links = await browser.page.locator("a").count()
        assert links > 0

    @pytest.mark.asyncio
    async def test_screenshot(self, browser):
        """测试截图功能"""
        await browser.goto("https://www.baidu.com")

        await browser.screenshot("/tmp/test_screenshot.png")
        assert Path("/tmp/test_screenshot.png").exists()

    @pytest.mark.asyncio
    async def test_multi_tab(self, browser):
        """测试多标签页"""
        # 创建多个标签页
        tab1 = await browser.new_tab("tab1")
        tab2 = await browser.new_tab("tab2")

        # 在不同标签页导航
        await browser.goto("https://www.baidu.com", tab_id=tab1.id)
        await browser.goto("https://www.baidu.com", tab_id=tab2.id)

        # 验证标签页数量
        tabs = browser.list_tabs()
        assert len(tabs) == 3  # default + 2 new tabs


class TestSmartWait:
    """智能等待测试"""

    @pytest.fixture
    async def browser(self):
        config = Config(headless=True)
        browser = EasyBrowser(config)
        await browser.start()
        yield browser
        await browser.close()

    @pytest.mark.asyncio
    async def test_wait_for_visible(self, browser):
        """测试等待可见"""
        await browser.goto("https://www.baidu.com")

        # 使用页面主体作为测试目标
        locator = browser.page.locator("body")
        result = await browser.smart_wait.wait_for(
            locator, WaitCondition.ATTACHED, timeout=10
        )

        assert result.success

    @pytest.mark.asyncio
    async def test_wait_for_stable(self, browser):
        """测试等待稳定"""
        await browser.goto("https://www.baidu.com")

        # 使用页面主体作为测试目标
        locator = browser.page.locator("body")
        result = await browser.smart_wait.wait_for(
            locator, WaitCondition.ATTACHED, timeout=10
        )

        assert result.success

    @pytest.mark.asyncio
    async def test_wait_for_text(self, browser):
        """测试等待文本"""
        await browser.goto("https://www.baidu.com")

        # 使用页面主体作为测试目标
        locator = browser.page.locator("body")
        result = await browser.smart_wait.wait_for(
            locator, WaitCondition.TEXT_NOT_EMPTY, timeout=10
        )

        assert result.success


class TestFormHandling:
    """表单处理测试"""
    
    @pytest.fixture
    async def browser(self):
        config = Config(headless=True)
        browser = EasyBrowser(config)
        await browser.start()
        yield browser
        await browser.close()
    
    @pytest.mark.asyncio
    async def test_form_fill(self, browser):
        """测试表单填充"""
        await browser.goto("https://www.baidu.com")
        
        form_handler = FormHandler(browser.page)
        
        # 测试获取表单值
        values = await form_handler.get_values()
        assert isinstance(values, dict)


class TestDataExtraction:
    """数据提取测试"""
    
    @pytest.fixture
    async def browser(self):
        config = Config(headless=True)
        browser = EasyBrowser(config)
        await browser.start()
        yield browser
        await browser.close()
    
    @pytest.mark.asyncio
    async def test_extract_links(self, browser):
        """测试链接提取"""
        await browser.goto("https://www.baidu.com")
        
        extractor = DataExtractor(browser.page)
        links = await extractor.extract_links()
        
        assert len(links) > 0
    
    @pytest.mark.asyncio
    async def test_extract_meta(self, browser):
        """测试Meta标签提取"""
        await browser.goto("https://www.baidu.com")
        
        extractor = DataExtractor(browser.page)
        meta = await extractor.extract_meta_tags()
        
        assert isinstance(meta, dict)


class TestNetworkMonitoring:
    """网络监控测试"""
    
    @pytest.fixture
    async def browser(self):
        config = Config(headless=True)
        browser = EasyBrowser(config)
        await browser.start()
        yield browser
        await browser.close()
    
    @pytest.mark.asyncio
    async def test_network_monitor(self, browser):
        """测试网络监控"""
        monitor = NetworkMonitor(browser.page)
        monitor.start()
        
        await browser.goto("https://www.baidu.com")
        
        # 获取请求日志
        requests = monitor.get_requests()
        assert len(requests) > 0
        
        # 获取摘要
        summary = monitor.summary()
        assert summary["total_requests"] > 0
        
        monitor.stop()


class TestPerformanceAnalysis:
    """性能分析测试"""
    
    @pytest.fixture
    async def browser(self):
        config = Config(headless=True)
        browser = EasyBrowser(config)
        await browser.start()
        yield browser
        await browser.close()
    
    @pytest.mark.asyncio
    async def test_performance_metrics(self, browser):
        """测试性能指标"""
        await browser.goto("https://www.baidu.com")
        
        analyzer = PerformanceAnalyzer(browser.page)
        metrics = await analyzer.measure_page_load()
        
        assert metrics.load > 0
        assert len(metrics.resources) > 0


class TestMobileEmulation:
    """移动端模拟测试"""
    
    def test_device_list(self):
        """测试设备列表"""
        from playwright_ez import DEVICES
        
        assert len(DEVICES) > 0
        assert "iphone-14" in DEVICES
        assert "pixel-7" in DEVICES
    
    def test_device_config(self):
        """测试设备配置"""
        emulator = DeviceEmulator()
        
        iphone = emulator.get_device("iphone-14")
        assert iphone is not None
        assert iphone.viewport_width > 0
        assert iphone.viewport_height > 0


class TestDataGenerator:
    """数据生成器测试"""
    
    def test_generate_name(self):
        """测试生成姓名"""
        name = fake_name()
        assert name is not None
        assert len(name) > 0
    
    def test_generate_email(self):
        """测试生成邮箱"""
        email = fake_email()
        assert "@" in email
    
    def test_generate_user(self):
        """测试生成用户"""
        user = fake_user()
        assert "name" in user
        assert "email" in user


class TestUtilityFunctions:
    """工具函数测试"""
    
    def test_random_string(self):
        """测试随机字符串"""
        from playwright_ez import random_string
        
        s = random_string(10)
        assert len(s) == 10
        
        s = random_string(20)
        assert len(s) == 20
    
    def test_mask_sensitive(self):
        """测试敏感信息脱敏"""
        from playwright_ez import mask_sensitive
        
        masked = mask_sensitive("1234567890")
        assert "*" in masked
    
    def test_timestamp(self):
        """测试时间戳"""
        from playwright_ez import timestamp, timestamp_ms
        
        ts = timestamp()
        assert ts > 0
        
        ts_ms = timestamp_ms()
        assert ts_ms > 0
    
    def test_is_valid_email(self):
        """测试邮箱验证"""
        from playwright_ez import is_valid_email
        
        assert is_valid_email("test@example.com") == True
        assert is_valid_email("invalid") == False
    
    def test_is_valid_phone(self):
        """测试手机号验证"""
        from playwright_ez import is_valid_phone
        
        assert is_valid_phone("13812345678") == True
        assert is_valid_phone("12345") == False


class TestDebugTools:
    """调试工具测试"""

    @pytest.fixture
    async def browser(self):
        config = Config(headless=True)
        browser = EasyBrowser(config)
        await browser.start()
        yield browser
        await browser.close()

    @pytest.mark.asyncio
    async def test_debugger(self, browser):
        """测试调试器"""
        await browser.goto("https://www.baidu.com")

        # 获取页面信息
        info = await Debugger(browser.page).capture_debug_info()
        assert info is not None
        assert info.url is not None

    @pytest.mark.asyncio
    async def test_assertion_helper(self, browser):
        """测试断言辅助"""
        await browser.goto("https://www.baidu.com")

        helper = AssertionHelper(browser.page)

        # 测试元素存在断言
        await helper.element_exists("body")  # 页面主体


class TestAntiDetection:
    """反检测测试"""
    
    def test_random_ua(self):
        """测试随机UA"""
        ua = AntiDetection.get_random_ua()
        
        assert ua is not None
        assert "Mozilla" in ua
    
    def test_random_screen(self):
        """测试随机屏幕尺寸"""
        screen = AntiDetection.get_random_screen()
        
        assert "width" in screen
        assert "height" in screen
        assert screen["width"] > 0


class TestVisualTesting:
    """视觉测试"""

    @pytest.fixture
    async def browser(self):
        config = Config(headless=True)
        browser = EasyBrowser(config)
        await browser.start()
        yield browser
        await browser.close()

    @pytest.mark.asyncio
    async def test_visual_tester(self, browser):
        """测试视觉测试器"""
        await browser.goto("https://www.baidu.com")

        visual = VisualTester(browser.page)

        # 设置基线
        await visual.set_baseline("baidu_homepage_test")

        # 再次访问并对比
        await browser.goto("https://www.baidu.com")

        # 截图
        await browser.screenshot("test_screenshot.png")

        # 验证截图文件存在
        assert Path("test_screenshot.png").exists()


# 运行测试
if __name__ == "__main__":
    pytest.main([__file__, "-v", "--asyncio-mode=auto"])
