"""
浏览器核心类 - 初始化和关闭逻辑
"""
from typing import Optional, TYPE_CHECKING

from playwright.async_api import (
    async_playwright,
    Browser,
    BrowserContext,
    Playwright,
)
from loguru import logger

from ..config import Config, get_config
from ..highlight import ElementHighlighter
from ..wait import SmartWait

if TYPE_CHECKING:
    from .tab import Tab


class BrowserCore:
    """
    浏览器核心功能 - 初始化和关闭

    这是所有 Mixin 的基类，提供：
    - __init__: 初始化配置和内部状态
    - start(): 启动浏览器
    - close(): 关闭浏览器
    - __aenter__, __aexit__: 上下文管理器
    """

    def __init__(self, config: Optional[Config] = None):
        self.config = config or get_config()
        self._playwright: Optional[Playwright] = None
        self._browser: Optional[Browser] = None
        self._context: Optional[BrowserContext] = None
        self._tabs: dict[str, "Tab"] = {}
        self._current_tab: Optional[str] = None

        # 原有模块
        self.highlighter = ElementHighlighter(self.config)
        self.smart_wait = SmartWait(self.config)

        self._tab_counter = 0

        # 核心模块懒加载属性
        self._network = None
        self._interceptor = None
        self._cookies = None
        self._session = None
        self._form = None
        self._visual = None
        self._recorder = None
        self._performance = None
        self._file = None
        self._extractor = None

        # 辅助类懒加载属性
        self._automation = None
        self._diagnostics = None
        self._scraper = None
        self._test = None
        self._monitor = None
        self._security = None
        self._ai = None

    async def start(self) -> "EasyBrowser":
        """启动浏览器"""
        from ..anti_detection import AntiDetection
        from .tab import Tab

        logger.info(f"启动浏览器: type={self.config.browser_type}, headless={self.config.headless}")

        self._playwright = await async_playwright().start()

        if self.config.browser_type == "chromium":
            browser_launcher = self._playwright.chromium
        elif self.config.browser_type == "firefox":
            browser_launcher = self._playwright.firefox
        elif self.config.browser_type == "webkit":
            browser_launcher = self._playwright.webkit
        else:
            raise ValueError(f"不支持的浏览器类型: {self.config.browser_type}")

        self._browser = await browser_launcher.launch(headless=self.config.headless)

        # 准备上下文选项
        context_options = {}

        # 窗口最大化或自定义视口
        if self.config.maximize_window:
            # 获取屏幕尺寸并设置为视口
            # 注意：需要在有界面的环境下才能获取真实屏幕尺寸
            context_options["viewport"] = None  # 让浏览器自动决定
            context_options["screen"] = {"width": 1920, "height": 1080}  # 默认大屏
        elif self.config.viewport_width and self.config.viewport_height:
            context_options["viewport"] = {
                "width": self.config.viewport_width,
                "height": self.config.viewport_height,
            }

        # 应用反检测配置
        if self.config.stealth_enabled:
            stealth_options = AntiDetection.get_context_options(
                user_agent=self.config.stealth_user_agent,
                viewport=self.config.stealth_viewport,
                locale=self.config.stealth_locale,
                timezone=self.config.stealth_timezone,
            )
            # 合并反检测选项（不覆盖已有的视口配置）
            for key, value in stealth_options.items():
                if key == "viewport" and "viewport" in context_options:
                    continue
                context_options[key] = value
            logger.debug(f"反检测已启用: ua={stealth_options.get('user_agent', 'random')[:50]}...")

        self._context = await self._browser.new_context(**context_options)

        # 创建第一个标签页
        await self.new_tab("default")

        # 如果配置了最大化，在启动后执行最大化
        if self.config.maximize_window and not self.config.headless:
            await self.maximize()

        logger.info("浏览器启动成功")
        return self

    async def close(self):
        """关闭浏览器"""
        logger.info("关闭浏览器")

        for tab_id in list(self._tabs.keys()):
            await self.close_tab(tab_id)

        if self._context:
            await self._context.close()
            self._context = None
        if self._browser:
            await self._browser.close()
            self._browser = None
        if self._playwright:
            await self._playwright.stop()
            self._playwright = None

        self._tabs.clear()
        self._current_tab = None
        logger.info("浏览器已关闭")

    async def __aenter__(self) -> "EasyBrowser":
        return await self.start()

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        await self.close()


# 前向引用类型
EasyBrowser = "EasyBrowser"
