"""
配置预设模块
提供常用场景的预设配置
"""
from typing import Dict, Any, Optional
from dataclasses import dataclass, field
from playwright_ez.config import Config


@dataclass
class PresetConfig:
    """预设配置"""
    name: str
    description: str
    config: Dict[str, Any] = field(default_factory=dict)


# 预设配置集合
PRESETS: Dict[str, PresetConfig] = {
    # 基础预设
    "default": PresetConfig(
        name="default",
        description="默认配置：无头模式，基本功能",
        config={
            "headless": True,
            "highlight_enabled": True,
            "log_level": "INFO",
        }
    ),
    
    # 调试模式
    "debug": PresetConfig(
        name="debug",
        description="调试模式：显示浏览器，详细日志，元素高亮",
        config={
            "headless": False,
            "highlight_enabled": True,
            "highlight_color": "red",
            "highlight_duration": 1.0,
            "log_level": "DEBUG",
            "default_timeout": 60.0,
        }
    ),
    
    # 快速模式
    "fast": PresetConfig(
        name="fast",
        description="快速模式：缩短等待时间，加快执行",
        config={
            "headless": True,
            "highlight_enabled": False,
            "log_level": "WARNING",
            "default_timeout": 10.0,
            "poll_interval": 0.05,
        }
    ),
    
    # 稳定模式
    "stable": PresetConfig(
        name="stable",
        description="稳定模式：增加等待时间，提高稳定性",
        config={
            "headless": True,
            "highlight_enabled": False,
            "log_level": "INFO",
            "default_timeout": 60.0,
            "poll_interval": 0.2,
            "stability_threshold": 5,
        }
    ),
    
    # 反检测模式
    "stealth": PresetConfig(
        name="stealth",
        description="隐身模式：隐藏自动化特征",
        config={
            "headless": True,
            "highlight_enabled": False,
            "log_level": "WARNING",
        }
    ),
    
    # 视觉测试模式
    "visual": PresetConfig(
        name="visual",
        description="视觉测试模式：启用截图和视觉对比",
        config={
            "headless": True,
            "highlight_enabled": False,
            "log_level": "INFO",
            "screenshot_on_error": True,
        }
    ),
    
    # 性能测试模式
    "performance": PresetConfig(
        name="performance",
        description="性能测试模式：记录性能指标",
        config={
            "headless": True,
            "highlight_enabled": False,
            "log_level": "INFO",
        }
    ),
    
    # 移动端模式
    "mobile": PresetConfig(
        name="mobile",
        description="移动端模式：模拟移动设备",
        config={
            "headless": True,
            "highlight_enabled": True,
            "log_level": "INFO",
        }
    ),
    
    # CI/CD模式
    "ci": PresetConfig(
        name="ci",
        description="CI/CD模式：无头，静默，快速失败",
        config={
            "headless": True,
            "highlight_enabled": False,
            "log_level": "ERROR",
            "default_timeout": 30.0,
        }
    ),
    
    # 开发模式
    "dev": PresetConfig(
        name="dev",
        description="开发模式：显示浏览器，详细日志，慢动作",
        config={
            "headless": False,
            "highlight_enabled": True,
            "highlight_duration": 1.5,
            "log_level": "DEBUG",
            "default_timeout": 120.0,
        }
    ),
}


def get_preset(name: str) -> Optional[Config]:
    """
    获取预设配置
    
    Args:
        name: 预设名称
        
    Returns:
        Config: 配置对象
    """
    if name not in PRESETS:
        raise ValueError(f"预设不存在: {name}. 可用: {list(PRESETS.keys())}")
    
    preset = PRESETS[name]
    return Config(**preset.config)


def list_presets() -> Dict[str, str]:
    """列出所有预设"""
    return {name: preset.description for name, preset in PRESETS.items()}


def create_custom_preset(name: str, description: str, **kwargs) -> PresetConfig:
    """
    创建自定义预设
    
    Args:
        name: 预设名称
        description: 描述
        **kwargs: 配置参数
        
    Returns:
        PresetConfig: 预设配置
    """
    preset = PresetConfig(
        name=name,
        description=description,
        config=kwargs,
    )
    
    PRESETS[name] = preset
    return preset


# 常用场景预设
SCENARIO_PRESETS = {
    # 登录场景
    "login": {
        "wait_after_fill": 0.5,
        "wait_after_click": 1.0,
        "timeout": 30,
    },
    
    # 表单场景
    "form": {
        "wait_after_fill": 0.3,
        "validate_before_submit": True,
    },
    
    # 数据抓取场景
    "scraping": {
        "wait_for_load": True,
        "scroll_to_load": True,
        "retry_count": 3,
    },
    
    # 电商场景
    "ecommerce": {
        "add_to_cart_wait": 2.0,
        "checkout_timeout": 60,
    },
}


def get_scenario_config(scenario: str) -> Dict[str, Any]:
    """获取场景配置"""
    return SCENARIO_PRESETS.get(scenario, {})


# 浏览器启动参数预设
BROWSER_ARGS = {
    "fast": [
        "--disable-extensions",
        "--disable-images",
        "--disable-javascript",
    ],
    
    "stealth": [
        "--disable-blink-features=AutomationControlled",
        "--disable-extensions",
        "--disable-infobars",
    ],
    
    "memory_saving": [
        "--disable-extensions",
        "--disable-plugins",
        "--disable-images",
        "--disable-background-networking",
    ],
    
    "full_features": [
        "--enable-features=NetworkService,NetworkServiceInProcess",
    ],
}


def get_browser_args(preset: str) -> list:
    """获取浏览器启动参数"""
    return BROWSER_ARGS.get(preset, [])
