"""
Browser utilities using Playwright for JavaScript-heavy sites
"""

import json
import asyncio
from typing import Dict, Any, List, Optional
from mcp.types import TextContent

from ..config import (
    PLAYWRIGHT_AVAILABLE, ANTI_DETECTION_HEADERS, 
    playwright_instance, browser_instance, logger
)


async def fetch_with_playwright(
    url: str, 
    timeout: int, 
    headers: Dict[str, Any], 
    wait_for: Optional[str] = None, 
    stealth: bool = False, 
    debug: bool = False
) -> List[TextContent]:
    """Fetch using Playwright (JS support)."""
    if not PLAYWRIGHT_AVAILABLE:
        from .requests_utils import fetch_with_requests
        return await fetch_with_requests(url, timeout, headers, debug)
        
    global playwright_instance, browser_instance
    
    try:
        # Initialize Playwright if needed
        if not playwright_instance:
            from playwright.async_api import async_playwright
            playwright_instance = await async_playwright().start()
            browser_instance = await playwright_instance.chromium.launch(
                headless=True,
                args=[
                    '--no-sandbox',
                    '--disable-blink-features=AutomationControlled',
                    '--disable-extensions',
                    '--disable-plugins',
                    '--disable-images' if not debug else '',
                ] + (['--disable-web-security'] if stealth else [])
            )
            
        # Create new context with anti-detection
        context_options = {
            "user_agent": headers.get("User-Agent", ANTI_DETECTION_HEADERS[0]),
            "viewport": {"width": 1920, "height": 1080},
            "ignore_https_errors": True,
        }
        
        if stealth:
            context_options.update({
                "java_script_enabled": True,
                "extra_http_headers": headers,
            })
            
        context = await browser_instance.new_context(**context_options)
        page = await context.new_page()
        
        # Anti-detection measures
        if stealth:
            await page.add_init_script("""
                Object.defineProperty(navigator, 'webdriver', {
                    get: () => undefined,
                });
                
                Object.defineProperty(navigator, 'plugins', {
                    get: () => [1, 2, 3, 4, 5],
                });
                
                Object.defineProperty(navigator, 'languages', {
                    get: () => ['en-US', 'en'],
                });
                
                window.chrome = {
                    runtime: {}
                };
            """)
        
        # Navigate to page
        response = await page.goto(url, timeout=timeout * 1000, wait_until="domcontentloaded")
        
        # Wait for specific element if requested
        if wait_for:
            try:
                await page.wait_for_selector(wait_for, timeout=timeout * 1000)
                logger.debug(f"Element {wait_for} loaded") if debug else None
            except Exception as e:
                logger.warning(f"Element {wait_for} not found: {e}") if debug else None
        
        # Get content
        html = await page.content()
        
        # Get cookies
        cookies = await context.cookies()
        cookies_info = {cookie['name']: cookie['value'] for cookie in cookies}
        
        # Get page info
        title = await page.title()
        current_url = page.url
        
        result = {
            "method": "playwright",
            "url": current_url,
            "original_url": url,
            "status_code": response.status if response else 200,
            "title": title,
            "html": html,
            "size": len(html),
            "cookies_count": len(cookies_info),
            "cookies": list(cookies_info.keys()) if debug else [],
            "stealth_mode": stealth,
            "wait_for": wait_for,
            "final_url": current_url if current_url != url else None
        }
        
        await context.close()
        return [TextContent(type="text", text=json.dumps(result, indent=2, ensure_ascii=False))]
        
    except Exception as e:
        error_msg = f"Playwright error: {str(e)}"
        logger.error(error_msg) if debug else None
        # Fallback to requests
        from .requests_utils import fetch_with_requests
        return await fetch_with_requests(url, timeout, headers, debug)
