"""
HTML fetching tools using unified Playwright browser session
"""

import json
import time
import logging
from typing import Dict, Any, List
from mcp.types import TextContent

from ..config import (
    authenticated_session, logger, ANTI_DETECTION_HEADERS
)
from ..utils.http_client import get_http_client


async def fetch_html_tool(args: Dict[str, Any]) -> List[TextContent]:
    """Fetch HTML content using unified Playwright browser session."""
    url = args["url"]
    timeout = args.get("timeout", 10)
    headers = args.get("headers", {})
    use_browser = args.get("use_browser", False)
    wait_for = args.get("wait_for")
    import_cookies_from = args.get("import_cookies_from")
    anti_detection = args.get("anti_detection", False)
    debug = args.get("debug", False)
    stealth = args.get("stealth", False)

    if debug:
        logger.setLevel(logging.DEBUG)
        logger.debug(f"Starting unified browser fetch for {url}")

    try:
        # Get unified HTTP client
        http_client = await get_http_client()

        # Apply anti-detection headers if requested
        if anti_detection:
            import random
            headers["User-Agent"] = random.choice(ANTI_DETECTION_HEADERS)
            headers.update({
                "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                "Accept-Language": "en-US,en;q=0.5",
                "Accept-Encoding": "gzip, deflate",
                "Connection": "keep-alive",
                "Upgrade-Insecure-Requests": "1",
            })

        # Use efficient API with browser session cookies
        logger.debug("🚀 Using efficient API with browser session") if debug else None

        # Get browser session cookies and use them for API request
        result = await http_client.get_with_session(url, timeout, headers, debug)

        # Add session information if available
        session_info = None
        if authenticated_session.get("active"):
            cookies_info = await http_client.get_cookies_info()
            if cookies_info["cookies_count"] > 0:
                session_info = {
                    "source": "unified_browser_session",
                    "login_url": authenticated_session.get("login_url"),
                    "cookies_count": cookies_info["cookies_count"],
                    "session_age_hours": (
                        (time.time() - authenticated_session.get("login_timestamp", time.time())) / 3600
                        if authenticated_session.get("login_timestamp") else 0
                    )
                }

        result["session_used"] = session_info

        return [TextContent(type="text", text=json.dumps(result, indent=2, ensure_ascii=False))]

    except Exception as e:
        error_msg = f"Failed to fetch {url}: {str(e)}"
        if debug:
            error_msg += f"\n{traceback.format_exc()}"
        return [TextContent(type="text", text=error_msg)]
