import logging
import mcp.types as types
from mcp.server.models import InitializationOptions
from mcp.server import NotificationOptions, Server
import mcp.server.stdio
from gmail_mcp.utils.GCP.gmail_search import search_emails
import importlib.metadata
import asyncio

from .tools import register_tools
from .intercepting_stream import InterceptingStream

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("gmail_mcp")

# Reduce noise from other loggers
logging.getLogger("mcp.server.lowlevel.server").setLevel(logging.WARNING)
logging.getLogger("mcp.server.stdio").setLevel(logging.WARNING)

# Track inflight requests
inflight_requests = {}

server = Server("gmail-mcp")


@server.progress_notification()
async def handle_progress_notification(progress_token: str | int, progress: float, total: float | None):
    """Handle progress notifications from the client."""
    try:
        request_id = str(progress_token)
        if request_id in inflight_requests:
            logger.info(
                f"Received progress update for request {request_id}: {progress}/{total}")
            if progress < 0:  # Use negative progress as a cancellation signal
                logger.info(f"Cancelling request {request_id}")
                inflight_requests[request_id] = "cancelled"
        else:
            logger.warning(
                f"Received progress for unknown request {request_id}")
    except Exception as e:
        logger.error(f"Error handling progress notification: {str(e)}")


async def main():
    """Start the MCP server with proper initialization."""
    try:
        logger.info("Starting Gmail MCP server")

        register_tools(server, inflight_requests)

        async with mcp.server.stdio.stdio_server() as (base_read_stream, write_stream):
            # Wrap the base_read_stream with our custom interceptor
            intercepted_read_stream = InterceptingStream(base_read_stream)

            await server.run(
                intercepted_read_stream,
                write_stream,
                InitializationOptions(
                    server_name="gmail_mcp",
                    server_version=importlib.metadata.version("gmail-mcp"),
                    capabilities=server.get_capabilities(
                        notification_options=NotificationOptions(
                            resources_changed=True,
                            prompts_changed=False,
                            tools_changed=False
                        ),
                        experimental_capabilities={},
                    ),
                ),
            )
    except Exception as e:
        logger.error(f"Error in main: {str(e)}")
        raise


async def perform_email_search(service, **kwargs):
    logger.info("Starting email search with parameters:")
    for key, value in kwargs.items():
        logger.info(f"  {key}: {value}")

    try:
        logger.info("Authenticating Gmail service...")
        # Add service verification
        if not service:
            logger.error("Gmail service not properly initialized")
            return "Error: Gmail service not initialized"

        logger.info("Executing search_emails function...")
        results = search_emails(service, **kwargs)

        if not results:
            logger.info("Search completed but no results found")
            return "No results found."

        logger.info(
            f"Search completed successfully. Found results: {bool(results)}")
        return results

    except Exception as e:
        logger.error(f"Error in perform_email_search: {str(e)}", exc_info=True)
        return f"Error performing search: {str(e)}"

if __name__ == "__main__":
    asyncio.run(main())
