#!/usr/bin/env python
"""
Google Ads MCP Server - Stdio Entry Point

This module provides stdio-based MCP server entry point for Claude Desktop.
"""

import os
import logging
from dotenv import load_dotenv
from mcp.server.fastmcp import FastMCP

# Load environment variables
load_dotenv()

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def initialize_mcp(mcp):
    """Initialize MCP tools."""
    logger.info("Initializing Google Ads MCP server (stdio mode)...")

    # Check if Google Ads credentials are available
    has_credentials = all([
        os.environ.get("GOOGLE_ADS_DEVELOPER_TOKEN"),
        os.environ.get("GOOGLE_ADS_CLIENT_ID"),
        os.environ.get("GOOGLE_ADS_CLIENT_SECRET"),
        os.environ.get("GOOGLE_ADS_REFRESH_TOKEN"),
        os.environ.get("GOOGLE_ADS_LOGIN_CUSTOMER_ID")
    ])

    if has_credentials:
        try:
            from google_ads_mcp_server.google_ads.client import GoogleAdsService
            from google_ads_mcp_server.mcp.tools import register_tools

            google_ads_service = GoogleAdsService()
            register_tools(mcp, google_ads_service)
            logger.info("MCP tools registered successfully with Google Ads API")
        except Exception as e:
            logger.warning(f"Failed to initialize Google Ads API: {e}, using demo mode")
            @mcp.tool()
            def test_health_check() -> str:
                """Health check tool to verify the MCP server is running."""
                return "Google Ads MCP Server is running in stdio mode. This is a demo tool."
    else:
        logger.info("Google Ads credentials not found, running in demo mode")
        @mcp.tool()
        def test_health_check() -> str:
            """Health check tool to verify the MCP server is running."""
            return "Google Ads MCP Server is running in stdio mode. This is a demo tool."

def main():
    """Main entry point for stdio MCP server."""
    logger.info("Starting Google Ads MCP server (stdio mode)...")

    # Initialize the MCP server
    mcp = FastMCP("Google Ads MCP Server")

    # Initialize MCP tools
    initialize_mcp(mcp)

    # Run MCP server in stdio mode
    logger.info("Running MCP server via stdio...")
    mcp.run(transport='stdio')

if __name__ == "__main__":
    main()