"""
元素高亮模块
"""
from typing import Optional
from playwright.async_api import Page, Locator, ElementHandle
from loguru import logger
from .config import get_config


class ElementHighlighter:
    """元素高亮器"""
    
    HIGHLIGHT_SCRIPT = """
    (element, args) => {
        const style = args[0];
        const duration = args[1];
        if (!element) return;
        
        // 保存原始样式
        const originalOutline = element.style.outline || '';
        const originalBackground = element.style.backgroundColor || '';
        const originalTransition = element.style.transition || '';
        
        // 应用高亮样式
        element.style.outline = style;
        element.style.transition = 'outline 0.1s ease-in-out';
        
        // 滚动到元素可见
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });
        
        // 持续一段时间后恢复
        setTimeout(() => {
            element.style.outline = originalOutline;
            element.style.backgroundColor = originalBackground;
            element.style.transition = originalTransition;
        }, duration * 1000);
    }
    """
    
    def __init__(self, config=None):
        self.config = config or get_config()
    
    async def highlight(
        self, 
        element: Locator, 
        color: Optional[str] = None,
        duration: Optional[float] = None
    ):
        """
        高亮显示元素
        
        Args:
            element: Playwright Locator 对象
            color: 高亮颜色，默认使用配置中的颜色
            duration: 高亮持续时间（秒），默认使用配置中的时间
        """
        if not self.config.highlight_enabled:
            return
            
        color = color or self.config.highlight_color
        duration = duration or self.config.highlight_duration
        style = self.config.highlight_style.format(color=color)
        
        try:
            await element.evaluate(self.HIGHLIGHT_SCRIPT, [style, duration])
            logger.debug(f"元素高亮: color={color}, duration={duration}s")
        except Exception as e:
            logger.warning(f"高亮元素失败: {e}")
    
    async def highlight_multiple(
        self, 
        elements: list[Locator], 
        color: Optional[str] = None,
        duration: Optional[float] = None
    ):
        """
        高亮多个元素
        
        Args:
            elements: Playwright Locator 对象列表
            color: 高亮颜色
            duration: 高亮持续时间
        """
        for i, element in enumerate(elements):
            await self.highlight(element, color, duration)
            if i < len(elements) - 1:
                # 元素之间稍微延迟，形成动画效果
                import asyncio
                await asyncio.sleep(0.1)


class HighlightContext:
    """高亮上下文管理器"""
    
    def __init__(self, highlighter: ElementHighlighter, element: Locator):
        self.highlighter = highlighter
        self.element = element
    
    async def __aenter__(self):
        await self.highlighter.highlight(self.element)
        return self.element
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        pass
