"""
配置模块
"""
from dataclasses import dataclass, field
from typing import Optional
from loguru import logger
import sys


@dataclass
class Config:
    """Playwright-EZ 配置"""

    # 浏览器配置
    headless: bool = True
    browser_type: str = "chromium"  # chromium, firefox, webkit

    # 窗口配置
    maximize_window: bool = False  # 启动时最大化窗口
    viewport_width: Optional[int] = None  # 视口宽度
    viewport_height: Optional[int] = None  # 视口高度

    # 弹窗配置
    auto_close_popup: bool = False  # 自动关闭弹窗
    popup_close_timeout: float = 5.0  # 弹窗关闭超时（秒）

    # 高亮配置
    highlight_enabled: bool = True
    highlight_color: str = "red"
    highlight_duration: float = 0.5  # 秒
    highlight_style: str = "2px solid {color}"

    # 等待配置
    default_timeout: float = 30.0  # 秒
    poll_interval: float = 0.1  # 轮询间隔
    stability_threshold: int = 3  # 元素稳定性阈值（连续N次检测到才算稳定）

    # 日志配置
    log_enabled: bool = True
    log_level: str = "DEBUG"
    log_format: str = "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"

    # 多标签配置
    max_tabs: int = 10  # 最大标签页数量

    # 截图配置
    screenshot_on_error: bool = True
    screenshot_dir: str = "./screenshots"

    # 反检测配置
    stealth_enabled: bool = True  # 默认启用反检测
    stealth_user_agent: Optional[str] = None  # 自定义UA（None则随机）
    stealth_locale: Optional[str] = None  # 自定义语言（None则随机）
    stealth_timezone: Optional[str] = None  # 自定义时区（None则随机）
    stealth_viewport: Optional[dict] = None  # 自定义视口（None则随机）

    # 人类化操作配置
    human_behavior_enabled: bool = False  # 默认关闭人类化操作
    human_type_delay_min: int = 50  # 打字最小延迟(毫秒)
    human_type_delay_max: int = 150  # 打字最大延迟(毫秒)
    human_mouse_steps: int = 15  # 鼠标移动步数
    human_scroll_steps: int = 8  # 滚动步数

    def setup_logger(self):
        """配置日志器"""
        logger.remove()
        if self.log_enabled:
            logger.add(
                sys.stderr,
                format=self.log_format,
                level=self.log_level,
                colorize=True,
            )
            logger.add(
                "playwright_ez.log",
                format=self.log_format,
                level=self.log_level,
                rotation="10 MB",
                retention="7 days",
            )
        return logger


# 全局配置实例
_global_config: Optional[Config] = None


def get_config() -> Config:
    """获取全局配置"""
    global _global_config
    if _global_config is None:
        _global_config = Config()
        _global_config.setup_logger()
    return _global_config


def set_config(config: Config):
    """设置全局配置"""
    global _global_config
    _global_config = config
    _global_config.setup_logger()
