"""
懒加载属性 Mixin
"""
from typing import Optional, TYPE_CHECKING

if TYPE_CHECKING:
    from playwright.async_api import Page, BrowserContext

    from ...network import NetworkMonitor, NetworkInterceptor
    from ...session import CookieManager, SessionManager
    from ...form import FormHandler
    from ...visual import VisualTester
    from ...recorder import ActionRecorder
    from ...performance import PerformanceAnalyzer
    from ...file_handler import FileHandler
    from ...extract import DataExtractor
    from ...browser_helpers import (
        AutomationHelper,
        DiagnosticsHelper,
        ScraperHelper,
        TestHelper,
        MonitoringHelper,
        SecurityHelper,
    )
    from ...ai import AIHelper


class PropertiesMixin:
    """懒加载属性功能"""

    # 这些属性由 BrowserCore 定义
    _context: Optional["BrowserContext"]
    _network: Optional["NetworkMonitor"]
    _interceptor: Optional["NetworkInterceptor"]
    _cookies: Optional["CookieManager"]
    _session: Optional["SessionManager"]
    _form: Optional["FormHandler"]
    _visual: Optional["VisualTester"]
    _recorder: Optional["ActionRecorder"]
    _performance: Optional["PerformanceAnalyzer"]
    _file: Optional["FileHandler"]
    _extractor: Optional["DataExtractor"]
    _automation: Optional["AutomationHelper"]
    _diagnostics: Optional["DiagnosticsHelper"]
    _scraper: Optional["ScraperHelper"]
    _test: Optional["TestHelper"]
    _monitor: Optional["MonitoringHelper"]
    _security: Optional["SecurityHelper"]
    _ai: Optional["AIHelper"]

    # ==================== 核心模块属性访问器 ====================

    @property
    def network(self) -> "NetworkMonitor":
        """
        获取网络监控器

        Returns:
            NetworkMonitor: 网络监控器实例
        """
        from ...network import NetworkMonitor

        if self._network is None:
            self._network = NetworkMonitor(self.page)
        return self._network

    @property
    def interceptor(self) -> "NetworkInterceptor":
        """
        获取网络拦截器

        Returns:
            NetworkInterceptor: 网络拦截器实例
        """
        from ...network import NetworkInterceptor

        if self._interceptor is None:
            self._interceptor = NetworkInterceptor(self.page)
        return self._interceptor

    @property
    def cookies(self) -> "CookieManager":
        """
        获取 Cookie 管理器

        Returns:
            CookieManager: Cookie 管理器实例
        """
        from ...session import CookieManager

        if self._cookies is None:
            if self._context is None:
                raise RuntimeError("浏览器上下文未初始化，请先启动浏览器")
            self._cookies = CookieManager(self._context)
        return self._cookies

    @property
    def session(self) -> "SessionManager":
        """
        获取会话管理器

        Returns:
            SessionManager: 会话管理器实例
        """
        from ...session import SessionManager

        if self._session is None:
            if self._context is None:
                raise RuntimeError("浏览器上下文未初始化，请先启动浏览器")
            self._session = SessionManager(self._context)
        return self._session

    @property
    def form(self) -> "FormHandler":
        """
        获取表单处理器

        Returns:
            FormHandler: 表单处理器实例
        """
        from ...form import FormHandler

        if self._form is None:
            self._form = FormHandler(self.page)
        return self._form

    @property
    def visual(self) -> "VisualTester":
        """
        获取视觉测试器

        Returns:
            VisualTester: 视觉测试器实例
        """
        from ...visual import VisualTester

        if self._visual is None:
            self._visual = VisualTester(self.page)
        return self._visual

    @property
    def recorder(self) -> "ActionRecorder":
        """
        获取操作录制器

        Returns:
            ActionRecorder: 操作录制器实例
        """
        from ...recorder import ActionRecorder

        if self._recorder is None:
            self._recorder = ActionRecorder(self.page)
        return self._recorder

    @property
    def performance(self) -> "PerformanceAnalyzer":
        """
        获取性能分析器

        Returns:
            PerformanceAnalyzer: 性能分析器实例
        """
        from ...performance import PerformanceAnalyzer

        if self._performance is None:
            self._performance = PerformanceAnalyzer(self.page)
        return self._performance

    @property
    def file(self) -> "FileHandler":
        """
        获取文件处理器

        Returns:
            FileHandler: 文件处理器实例
        """
        from ...file_handler import FileHandler

        if self._file is None:
            self._file = FileHandler(self.page)
        return self._file

    @property
    def extractor(self) -> "DataExtractor":
        """
        获取数据提取器

        Returns:
            DataExtractor: 数据提取器实例
        """
        from ...extract import DataExtractor

        if self._extractor is None:
            self._extractor = DataExtractor(self.page)
        return self._extractor

    # ==================== 辅助类属性访问器 ====================

    @property
    def automation(self) -> "AutomationHelper":
        """
        获取自动化辅助类

        使用方式:
            browser.automation.infinite_scroll  # InfiniteScrollHandler
            browser.automation.pagination       # PaginationNavigator
            browser.automation.iframe           # IframeManager
            browser.automation.drag_drop        # DragDropHelper
            browser.automation.file             # FileHandler

        Returns:
            AutomationHelper: 自动化辅助类实例
        """
        from ...browser_helpers import AutomationHelper

        if self._automation is None:
            self._automation = AutomationHelper(lambda: self.page)
        return self._automation

    @property
    def diagnostics(self) -> "DiagnosticsHelper":
        """
        获取诊断辅助类

        使用方式:
            browser.diagnostics.console  # ConsoleMonitor
            browser.diagnostics.error    # ErrorAnalyzer

        Returns:
            DiagnosticsHelper: 诊断辅助类实例
        """
        from ...browser_helpers import DiagnosticsHelper

        if self._diagnostics is None:
            self._diagnostics = DiagnosticsHelper(lambda: self.page)
        return self._diagnostics

    @property
    def scraper(self) -> "ScraperHelper":
        """
        获取数据采集辅助类

        使用方式:
            browser.scraper.rate_limiter  # RateLimiter
            browser.scraper.validator     # DataValidator

        Returns:
            ScraperHelper: 数据采集辅助类实例
        """
        from ...browser_helpers import ScraperHelper

        if self._scraper is None:
            self._scraper = ScraperHelper(lambda: self.page)
        return self._scraper

    @property
    def test(self) -> "TestHelper":
        """
        获取测试辅助类

        使用方式:
            browser.test.accessibility  # AccessibilityChecker

        Returns:
            TestHelper: 测试辅助类实例
        """
        from ...browser_helpers import TestHelper

        if self._test is None:
            self._test = TestHelper(lambda: self.page)
        return self._test

    @property
    def monitor(self) -> "MonitoringHelper":
        """
        获取监控辅助类

        使用方式:
            browser.monitor.seo  # SEOChecker

        Returns:
            MonitoringHelper: 监控辅助类实例
        """
        from ...browser_helpers import MonitoringHelper

        if self._monitor is None:
            self._monitor = MonitoringHelper(lambda: self.page)
        return self._monitor

    @property
    def security(self) -> "SecurityHelper":
        """
        获取安全辅助类

        使用方式:
            browser.security.scanner  # SecurityScanner

        Returns:
            SecurityHelper: 安全辅助类实例
        """
        from ...browser_helpers import SecurityHelper

        if self._security is None:
            self._security = SecurityHelper(lambda: self.page)
        return self._security

    @property
    def ai(self) -> "AIHelper":
        """
        获取 AI 辅助类

        使用方式:
            # 智能选择器建议
            suggestions = await browser.ai.suggest_selectors("登录按钮")

            # 错误诊断
            diagnosis = await browser.ai.diagnose_error(error)

            # 生成测试代码
            code = await browser.ai.generate_test_code("登录流程")

        Returns:
            AIHelper: AI 辅助类实例
        """
        from ...ai import AIHelper

        if self._ai is None:
            self._ai = AIHelper(self.page)
        return self._ai

    def _reset_helpers(self):
        """
        重置所有辅助类实例
        当切换标签页时调用，确保使用正确的 Page 对象
        """
        # 重置核心模块
        self._network = None
        self._interceptor = None
        self._form = None
        self._visual = None
        self._recorder = None
        self._performance = None
        self._file = None
        self._extractor = None

        # 重置辅助类
        if self._automation:
            self._automation.reset()
        if self._diagnostics:
            self._diagnostics.reset()
        if self._scraper:
            self._scraper.reset()
        if self._test:
            self._test.reset()
        if self._monitor:
            self._monitor.reset()
        if self._security:
            self._security.reset()
        self._ai = None
