"""
诊断辅助类
整合 diagnostics 子模块，提供统一访问入口
"""
from typing import Callable, Optional
from playwright.async_api import Page

from ..diagnostics import (
    ConsoleMonitor,
    ConsoleMonitorConfig,
    ErrorAnalyzer,
    PageSnapshot,
    SnapshotConfig,
)


class DiagnosticsHelper:
    """
    诊断辅助类
    整合 diagnostics 子模块

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

    def __init__(self, get_page: Callable[[], Page]):
        """
        初始化诊断辅助类

        Args:
            get_page: 获取当前 Page 对象的回调函数
        """
        self._get_page = get_page
        self._console: Optional[ConsoleMonitor] = None
        self._error: Optional[ErrorAnalyzer] = None
        self._snapshot: Optional[PageSnapshot] = None
        self._console_config: Optional[ConsoleMonitorConfig] = None
        self._snapshot_config: Optional[SnapshotConfig] = None

    @property
    def console(self) -> ConsoleMonitor:
        """
        获取控制台监控器

        Returns:
            ConsoleMonitor: 控制台监控器实例
        """
        if self._console is None:
            self._console = ConsoleMonitor(
                self._get_page(),
                self._console_config
            )
        return self._console

    @property
    def error(self) -> ErrorAnalyzer:
        """
        获取错误分析器

        Returns:
            ErrorAnalyzer: 错误分析器实例
        """
        if self._error is None:
            self._error = ErrorAnalyzer(self._get_page())
        return self._error

    @property
    def snapshot(self) -> PageSnapshot:
        """
        获取页面快照工具

        Returns:
            PageSnapshot: 页面快照实例
        """
        if self._snapshot is None:
            self._snapshot = PageSnapshot(
                self._get_page(),
                self._snapshot_config
            )
        return self._snapshot

    def set_console_config(self, config: ConsoleMonitorConfig):
        """
        设置控制台监控配置

        Args:
            config: 控制台监控配置
        """
        self._console_config = config
        # 重置实例以应用新配置
        self._console = None

    def set_snapshot_config(self, config: SnapshotConfig):
        """
        设置快照配置

        Args:
            config: 快照配置
        """
        self._snapshot_config = config
        self._snapshot = None

    def reset(self):
        """
        重置所有实例
        当切换标签页时调用，确保使用正确的 Page 对象
        """
        self._console = None
        self._error = None
        self._snapshot = None
