"""
Environment Variable Test MCP Server
Simple FastMCP server to test environment variable passing in Docker
"""

import os
import logging
from fastmcp import FastMCP

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

# Create FastMCP instance
test_mcp = FastMCP("Environment Test MCP Server")

@test_mcp.tool
def list_all_env_vars():
    """List all environment variables"""
    logger.info("Listing all environment variables")
    return dict(os.environ)

@test_mcp.tool
def get_env_var(var_name: str):
    """Get a specific environment variable

    Args:
        var_name: Name of the environment variable to retrieve
    """
    logger.info(f"Getting environment variable: {var_name}")
    value = os.getenv(var_name)
    return {
        "variable": var_name,
        "value": value,
        "exists": value is not None
    }

@test_mcp.tool
def check_jira_env():
    """Check specifically for Jira environment variables"""
    logger.info("Checking Jira environment variables")

    jira_vars = {
        "JIRA_URL": os.getenv("JIRA_URL"),
        "JIRA_PERSONAL_TOKEN": os.getenv("JIRA_PERSONAL_TOKEN"),
        "JIRA_USERNAME": os.getenv("JIRA_USERNAME"),
        "JIRA_API_TOKEN": os.getenv("JIRA_API_TOKEN")
    }

    return {
        var: {
            "value": value,
            "exists": value is not None,
            "length": len(value) if value else 0
        }
        for var, value in jira_vars.items()
    }

@test_mcp.tool
def server_info():
    """Get server information and basic environment details"""
    logger.info("Getting server information")

    return {
        "server_name": "Environment Test MCP Server",
        "python_version": os.sys.version,
        "working_directory": os.getcwd(),
        "hostname": os.getenv("HOSTNAME", "unknown"),
        "path": os.getenv("PATH", ""),
        "total_env_vars": len(os.environ)
    }

def main():
    """Run the test MCP server"""

    # Log startup information
    logger.info("🧪 Environment Test MCP Server Starting...")
    logger.info(f"   - Working Directory: {os.getcwd()}")
    logger.info(f"   - Total ENV vars: {len(os.environ)}")
    logger.info(f"   - JIRA_URL: {'✅ Set' if os.getenv('JIRA_URL') else '❌ Missing'}")
    logger.info(f"   - JIRA_PERSONAL_TOKEN: {'✅ Set' if os.getenv('JIRA_PERSONAL_TOKEN') else '❌ Missing'}")

    # Configure server settings
    port = int(os.getenv('MCP_PORT', 8001))
    host = os.getenv('MCP_HOST', '0.0.0.0')

    logger.info(f"🚀 Starting Test MCP Server on {host}:{port}")
    logger.info("📍 Available endpoints:")
    logger.info(f"   - HTTP: http://{host}:{port}/mcp")
    logger.info("🔧 Available tools:")
    logger.info("   - list_all_env_vars: List all environment variables")
    logger.info("   - get_env_var: Get specific environment variable")
    logger.info("   - check_jira_env: Check Jira environment variables")
    logger.info("   - server_info: Get server information")
    logger.info("💡 Use Ctrl+C to stop the server")

    # Run FastMCP server with HTTP transport
    test_mcp.run(transport="http", host=host, port=port, path="/mcp")

if __name__ == "__main__":
    main()