"""
Simplified MCP Configuration Management Server
==============================================

Provides simplified configuration management tools for Storm Logger MCP servers
without **kwargs to avoid FastMCP compatibility issues.
"""

import asyncio
import json
import os
from typing import Dict, Any, Optional, List

from fastmcp import FastMCP
# Import config manager with flexible import handling
try:
    # Try relative imports first (when run as module)
    from ..config_manager import config_manager, ConfigSource
except ImportError:
    # Fall back to absolute imports (when run from parent directory)
    from config_manager import config_manager, ConfigSource

# Initialize the FastMCP server
server = FastMCP("Configuration Management Server")

@server.tool(tags={"configuration", "management"})
def get_server_config(server_name: str) -> Dict:
    """
    Get configuration for a specific MCP server.
    
    Args:
        server_name: Name of the server to get configuration for
        
    Returns:
        Dict containing server configuration and metadata
    """
    config = config_manager.get_server_config(server_name)
    
    if not config:
        return {
            "status": "error",
            "message": f"Server '{server_name}' not found in configuration",
            "available_servers": list(config_manager.config.servers.keys())
        }
    
    return {
        "status": "success",
        "server_name": server_name,
        "config": {
            "enabled": config.enabled,
            "max_connections": config.max_connections,
            "request_timeout": config.request_timeout,
            "health_check_interval": config.health_check_interval,
            "log_level": config.log_level,
            "tools_enabled": config.tools_enabled,
            "custom_settings": config.custom_settings
        },
        "config_sources": {
            key: source.value for key, source in config_manager.config_sources.items()
            if key.startswith(f"servers.{server_name}")
        }
    }

@server.tool(tags={"configuration", "management"})
def update_server_enabled(server_name: str, enabled: bool) -> Dict:
    """Update server enabled status."""
    try:
        config_manager.update_server_config(server_name, enabled=enabled)
        return {
            "status": "success",
            "message": f"Server '{server_name}' enabled status updated to {enabled}",
            "server_name": server_name,
            "enabled": enabled
        }
    except Exception as e:
        return {
            "status": "error",
            "message": f"Failed to update server enabled status: {str(e)}",
            "server_name": server_name
        }

@server.tool(tags={"configuration", "management"})
def update_server_max_connections(server_name: str, max_connections: int) -> Dict:
    """Update server max connections."""
    try:
        config_manager.update_server_config(server_name, max_connections=max_connections)
        return {
            "status": "success",
            "message": f"Server '{server_name}' max connections updated to {max_connections}",
            "server_name": server_name,
            "max_connections": max_connections
        }
    except Exception as e:
        return {
            "status": "error",
            "message": f"Failed to update server max connections: {str(e)}",
            "server_name": server_name
        }

@server.tool(tags={"configuration", "management"})
def update_server_log_level(server_name: str, log_level: str) -> Dict:
    """Update server log level."""
    try:
        valid_levels = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
        if log_level not in valid_levels:
            return {
                "status": "error",
                "message": f"Invalid log level. Valid levels: {valid_levels}",
                "server_name": server_name
            }
        
        config_manager.update_server_config(server_name, log_level=log_level)
        return {
            "status": "success",
            "message": f"Server '{server_name}' log level updated to {log_level}",
            "server_name": server_name,
            "log_level": log_level
        }
    except Exception as e:
        return {
            "status": "error",
            "message": f"Failed to update server log level: {str(e)}",
            "server_name": server_name
        }

@server.tool(tags={"configuration", "monitoring"})
def get_monitoring_config() -> Dict:
    """
    Get monitoring system configuration.
    
    Returns:
        Dict containing monitoring configuration
    """
    config = config_manager.get_monitoring_config()
    
    return {
        "status": "success",
        "monitoring_config": {
            "enabled": config.enabled,
            "metrics_collection_interval": config.metrics_collection_interval,
            "dashboard_enabled": config.dashboard_enabled,
            "dashboard_port": config.dashboard_port,
            "alert_thresholds": config.alert_thresholds,
            "performance_monitoring": config.performance_monitoring,
            "business_intelligence": config.business_intelligence
        },
        "config_sources": {
            key: source.value for key, source in config_manager.config_sources.items()
            if key.startswith("monitoring")
        }
    }

@server.tool(tags={"configuration", "monitoring"})
def update_monitoring_enabled(enabled: bool) -> Dict:
    """Update monitoring enabled status."""
    try:
        config_manager.update_monitoring_config(enabled=enabled)
        return {
            "status": "success",
            "message": f"Monitoring enabled status updated to {enabled}",
            "enabled": enabled
        }
    except Exception as e:
        return {
            "status": "error",
            "message": f"Failed to update monitoring enabled status: {str(e)}"
        }

@server.tool(tags={"configuration", "monitoring"})
def update_dashboard_port(port: int) -> Dict:
    """Update dashboard port."""
    try:
        if port < 1 or port > 65535:
            return {
                "status": "error",
                "message": "Port must be between 1 and 65535"
            }
        
        config_manager.update_monitoring_config(dashboard_port=port)
        return {
            "status": "success",
            "message": f"Dashboard port updated to {port}",
            "dashboard_port": port
        }
    except Exception as e:
        return {
            "status": "error",
            "message": f"Failed to update dashboard port: {str(e)}"
        }

@server.tool(tags={"configuration", "global"})
def get_global_settings() -> Dict:
    """
    Get global settings.
    
    Returns:
        Dict containing global settings
    """
    settings = config_manager.get_global_settings()
    
    return {
        "status": "success",
        "global_settings": settings,
        "config_sources": {
            key: source.value for key, source in config_manager.config_sources.items()
            if key.startswith("global_settings")
        }
    }

@server.tool(tags={"configuration", "global"})
def update_debug_mode(debug_mode: bool) -> Dict:
    """Update debug mode setting."""
    try:
        config_manager.update_global_settings(debug_mode=debug_mode)
        return {
            "status": "success",
            "message": f"Debug mode updated to {debug_mode}",
            "debug_mode": debug_mode
        }
    except Exception as e:
        return {
            "status": "error",
            "message": f"Failed to update debug mode: {str(e)}"
        }

@server.tool(tags={"configuration", "global"})
def update_environment(environment: str) -> Dict:
    """Update environment setting."""
    try:
        valid_environments = ["development", "staging", "production"]
        if environment not in valid_environments:
            return {
                "status": "error",
                "message": f"Invalid environment. Valid environments: {valid_environments}"
            }
        
        config_manager.update_global_settings(environment=environment)
        return {
            "status": "success",
            "message": f"Environment updated to {environment}",
            "environment": environment
        }
    except Exception as e:
        return {
            "status": "error",
            "message": f"Failed to update environment: {str(e)}"
        }

@server.tool(tags={"configuration", "management"})
def get_config_summary() -> Dict:
    """
    Get complete configuration summary.
    
    Returns:
        Dict containing complete configuration summary
    """
    try:
        summary = config_manager.get_config_summary()
        
        return {
            "status": "success",
            "config_summary": summary,
            "statistics": {
                "total_servers": len(summary['servers']),
                "enabled_servers": sum(1 for s in summary['servers'].values() if s['enabled']),
                "config_sources": len(summary['config_sources']),
                "config_file": summary['config_file'],
                "last_modified": summary['last_modified']
            }
        }
        
    except Exception as e:
        return {
            "status": "error",
            "message": f"Failed to get configuration summary: {str(e)}"
        }

@server.tool(tags={"configuration", "import_export"})
def export_config(format: str = "json") -> Dict:
    """
    Export current configuration.
    
    Args:
        format: Export format (json, yaml)
        
    Returns:
        Dict containing exported configuration
    """
    try:
        exported_config = config_manager.export_config(format)
        
        return {
            "status": "success",
            "format": format,
            "config": exported_config,
            "size": len(exported_config),
            "message": f"Configuration exported successfully in {format} format"
        }
        
    except Exception as e:
        return {
            "status": "error",
            "message": f"Failed to export configuration: {str(e)}"
        }

@server.tool(tags={"configuration", "validation"})
def validate_config() -> Dict:
    """
    Validate current configuration.
    
    Returns:
        Dict containing validation results
    """
    try:
        # Trigger validation
        config_manager._validate_configuration()
        
        return {
            "status": "success",
            "message": "Configuration validation passed",
            "valid": True
        }
        
    except Exception as e:
        return {
            "status": "error",
            "message": f"Configuration validation failed: {str(e)}",
            "valid": False
        }

@server.tool(tags={"configuration", "environment"})
def get_environment_variables() -> Dict:
    """
    Get MCP-related environment variables.
    
    Returns:
        Dict containing environment variables
    """
    env_vars = {}
    mcp_prefixes = ['MCP_', 'STORM_', 'FASTMCP_']
    
    for key, value in os.environ.items():
        if any(key.startswith(prefix) for prefix in mcp_prefixes):
            env_vars[key] = value
    
    return {
        "status": "success",
        "environment_variables": env_vars,
        "count": len(env_vars),
        "message": "Environment variables retrieved successfully"
    }

@server.tool(tags={"health", "internal"})
def health_check() -> Dict:
    """Health check for configuration server."""
    import time
    checks = {
        "server_operational": True,
        "tools_available": True,
        "config_manager_loaded": True,
        "config_file_accessible": True
    }
    
    try:
        # Test config manager
        config_manager.get_config_summary()
        checks["config_manager_loaded"] = True
        
        # Test config file
        if hasattr(config_manager, 'config_file'):
            checks["config_file_accessible"] = config_manager.config_file.parent.exists()
        
    except Exception as e:
        checks["config_manager_loaded"] = False
        checks["config_file_accessible"] = False
    
    return {
        "status": "healthy" if all(checks.values()) else "warning",
        "checks": checks,
        "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "server": "config"
    }

if __name__ == "__main__":
    server.run()