"""
Web Parser MCP Server - Hybrid Architecture v3.7.5
🚀 EFFICIENT API + BROWSER SESSION! Best of both worlds

🎯 HYBRID ARCHITECTURE:
- 📁 src/config.py - global configuration and browser session management
- 📁 src/schemas.py - data extraction schemas
- 📁 src/tools/definitions/ - 6 functional tool groups
- 📁 src/utils/ - utility functions (api_client, http_client, detection)
- 📁 src/session/ - session management utilities

✨ TRANSFORMATION: main.py (3838 lines) → main.py (125 lines) [-97%!]

🏗️ TOOL GROUPS:
- 🔍 fetch_tools: HTML fetching with SessionAPIClient (4 tools)
- 🔐 auth_tools: Form and browser authentication (2 tools)
- 📊 session_tools: Session management and auth setup (5 tools)
- 🧭 navigation_tools: Pagination and parallel processing (3 tools)
- 🎬 media_tools: Screenshots and media download (2 tools)
- 📋 data_tools: Structured data processing (3 tools)

🚀 NEW HYBRID APPROACH:
- Browser login → creates authenticated session with cookies
- All tools → use SessionAPIClient with browser cookies
- Perfect session sharing, fast API requests, browser authentication
"""

import asyncio
import sys
from typing import Any, Dict

from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import TextContent

# Import configuration and tools
from src.config import (
    browser_instance,
    cleanup_browser_session,
    logger,
    playwright_instance,
)
from src.tools import (
    api_batch_test_tool,
    api_test_tool,
    auto_paginate_tool,
    browser_login_tool,
    cache_results_tool,
    clear_cache_tool,
    clear_session_tool,
    debug_screenshot_tool,
    discover_plugins_tool,
    download_media_tool,
    extract_dynamic_content_tool,
    extract_links_tool,
    extract_structured_data_tool,
    extract_text_tool,
    fetch_html_tool,
    find_elements_tool,
    get_all_tools,
    get_cache_stats_tool,
    get_connection_stats_tool,
    get_performance_metrics_tool,
    get_plugin_tools_tool,
    get_session_info_tool,
    get_system_health_tool,
    import_browser_cookies_tool,
    infinite_scroll_tool,
    list_plugins_tool,
    load_plugin_tool,
    login_form_tool,
    parallel_fetch_tool,
    parse_advanced_tool,
    parse_page_tool,
    run_diagnostic_tool,
    set_basic_auth_tool,
    set_oauth_token_tool,
    unload_plugin_tool,
)
from src.utils.middleware import process_with_middleware

# Initialize MCP server
server = Server("web-parser-mcp")


@server.list_tools()
async def list_tools():
    """List available web parsing tools."""
    return get_all_tools()


# Tool registry for middleware processing
TOOL_REGISTRY = {
    "fetch_html": fetch_html_tool,
    "extract_text": extract_text_tool,
    "find_elements": find_elements_tool,
    "extract_links": extract_links_tool,
    "login_form": login_form_tool,
    "set_basic_auth": set_basic_auth_tool,
    "get_session_info": get_session_info_tool,
    "set_oauth_token": set_oauth_token_tool,
    "browser_login": browser_login_tool,
    "auto_paginate": auto_paginate_tool,
    "debug_screenshot": debug_screenshot_tool,
    "parallel_fetch": parallel_fetch_tool,
    "infinite_scroll": infinite_scroll_tool,
    "extract_structured_data": extract_structured_data_tool,
    "download_media": download_media_tool,
    "cache_results": cache_results_tool,
    "clear_session": clear_session_tool,
    "import_browser_cookies": import_browser_cookies_tool,
    "parse_page": parse_page_tool,
    "get_system_health": get_system_health_tool,
    "get_performance_metrics": get_performance_metrics_tool,
    "get_cache_stats": get_cache_stats_tool,
    "clear_cache": clear_cache_tool,
    "get_connection_stats": get_connection_stats_tool,
    "run_diagnostic": run_diagnostic_tool,
    "api_test": api_test_tool,
    "api_batch_test": api_batch_test_tool,
    "parse_advanced": parse_advanced_tool,
    "extract_dynamic_content": extract_dynamic_content_tool,
    "load_plugin": load_plugin_tool,
    "unload_plugin": unload_plugin_tool,
    "list_plugins": list_plugins_tool,
    "discover_plugins": discover_plugins_tool,
    "get_plugin_tools": get_plugin_tools_tool,
}


@server.call_tool()
async def call_tool(name: str, arguments: Dict[str, Any]):
    """Handle tool calls for web parsing with middleware processing."""
    try:
        # Get tool function from registry
        tool_function = TOOL_REGISTRY.get(name)
        if not tool_function:
            return [{"type": "text", "text": f"Unknown tool: {name}"}]

        # Process through middleware chain
        return await process_with_middleware(name, arguments, tool_function)

    except Exception as e:
        import traceback

        error_msg = f"Error in {name}: {str(e)}\n{traceback.format_exc()}"
        logger.error(error_msg)
        return [{"type": "text", "text": error_msg}]


async def main():
    """Run the MCP server."""
    try:
        async with stdio_server() as streams:
            await server.run(streams[0], streams[1], server.create_initialization_options())
    except KeyboardInterrupt:
        pass
    except Exception as e:
        print(f"Server error: {e}", file=sys.stderr)
    finally:
        # Cleanup unified browser session
        await cleanup_browser_session()


if __name__ == "__main__":
    asyncio.run(main())
