"""
Storm Logger Enterprise MCP Server
A professional, enterprise-grade MCP server for Storm Logger development with business intelligence focus.
"""

import os
import yaml
from typing import Any, Dict, List, Optional, Set
from contextlib import asynccontextmanager
from pathlib import Path

from fastmcp import FastMCP
from fastmcp.server import FastMCP as MCP

# Import specialized server modules with flexible import handling
try:
    # Try relative imports first (when run as module)
    from .servers.coverage import create_coverage_server
    from .servers.testing import create_testing_server
    from .servers.security import create_security_server
    from .servers.patterns import create_patterns_server
    from .servers.gitlab import create_gitlab_server
    from .servers.python import create_python_server
    from .servers.core import create_core_server
    from .servers.config_simple import server as config_server
except ImportError:
    # Fall back to absolute imports (when run directly)
    from servers.coverage import create_coverage_server
    from servers.testing import create_testing_server
    from servers.security import create_security_server
    from servers.patterns import create_patterns_server
    from servers.gitlab import create_gitlab_server
    from servers.python import create_python_server
    from servers.core import create_core_server
    from servers.config_simple import server as config_server

# Configuration
DEFAULT_PROJECT_PATH = "/home/mathew/python-3.10.12-Projects/storm_logger"
STORM_MCP_VERSION = "2.0.0"


def custom_yaml_serializer(data: Any) -> str:
    """
    Custom YAML serializer for better readability of tool outputs.
    
    Args:
        data: Any data structure to serialize
        
    Returns:
        YAML formatted string
    """
    try:
        return yaml.dump(
            data,
            default_flow_style=False,
            allow_unicode=True,
            sort_keys=False,
            width=100,
            indent=2
        )
    except Exception:
        # Fallback to default JSON serialization
        import json
        return json.dumps(data, indent=2)


@asynccontextmanager
async def lifespan(server: MCP):
    """
    Server lifespan management for startup and shutdown logic.
    
    Args:
        server: The MCP server instance
    """
    # Startup
    print(f"🚀 Starting Storm Logger MCP Server v{STORM_MCP_VERSION}")
    print(f"📁 Project Path: {DEFAULT_PROJECT_PATH}")
    print(f"🏷️  Tag Filtering: {server.include_tags or 'None'} (include), {server.exclude_tags or 'None'} (exclude)")
    
    # Validate project path
    if not Path(DEFAULT_PROJECT_PATH).exists():
        print(f"⚠️  Warning: Project path {DEFAULT_PROJECT_PATH} does not exist")
    
    yield
    
    # Shutdown
    print("🛑 Shutting down Storm Logger MCP Server")


def create_storm_mcp_server() -> FastMCP:
    """
    Create and configure the enterprise Storm Logger MCP server.
    
    Returns:
        Configured FastMCP server instance with all specialized servers mounted
    """
    # Determine tag filtering based on environment
    environment = os.getenv("STORM_MCP_ENV", "development")
    
    # Configure tag filtering based on environment
    include_tags: Optional[Set[str]] = None
    exclude_tags: Optional[Set[str]] = None
    
    if environment == "production":
        include_tags = {"public", "stable"}
        exclude_tags = {"experimental", "internal", "debug"}
    elif environment == "testing":
        include_tags = {"public", "testing", "stable"}
        exclude_tags = {"experimental", "debug"}
    elif environment == "internal":
        include_tags = {"public", "internal", "stable"}
        exclude_tags = {"experimental"}
    # Development environment includes all tags
    
    # Create the main server with enterprise configuration
    server = FastMCP(
        name="Storm Logger Enterprise MCP Server",
        instructions="""
        This is the Storm Logger Enterprise MCP Server - your comprehensive development assistant 
        for the Storm Logger project and its $50M revenue ecosystem.
        
        🎯 **Core Capabilities:**
        - **Coverage Intelligence**: Analyze test coverage gaps with business impact assessment
        - **Test Generation**: Create enterprise-grade tests for critical modules
        - **Security & Compliance**: GDPR, HIPAA, SOC2 compliance tools
        - **Pattern Management**: Escape regex hell with intelligent pattern matching
        - **GitLab CI/CD**: Optimize pipelines for enterprise deployment
        - **Python Development**: Code analysis, refactoring, and documentation
        
        🚀 **Business Intelligence Focus:**
        All tools are designed with Storm Logger's business goals in mind:
        - Revenue impact analysis for coverage decisions
        - Enterprise readiness assessment
        - Performance optimization for 6M logs/sec capability
        - Compliance tracking for Fortune 500 adoption
        
        💡 **Getting Started:**
        1. Use `analyze_coverage_gaps` to understand your current test coverage
        2. Generate missing tests with `generate_missing_tests`
        3. Enhance existing tests with `enhance_existing_tests`
        4. Track progress with `track_coverage_progress`
        
        🏷️ **Tag System:**
        Tools are organized by tags: public, internal, admin, experimental, stable
        """,
        dependencies=[
            "fastmcp>=0.1.0",
            "pyyaml>=6.0",
            "rich>=13.0.0",
            "pytest>=7.0.0",
            "coverage>=7.0.0"
        ],
        include_tags=include_tags,
        exclude_tags=exclude_tags,
        on_duplicate_tools="warn",
        on_duplicate_resources="warn",
        on_duplicate_prompts="replace",
        tool_serializer=custom_yaml_serializer,
        lifespan=lifespan,
        # Additional enterprise settings
        mask_error_details=os.getenv("STORM_MCP_MASK_ERRORS", "false").lower() == "true"
    )
    
    # Mount specialized servers
    mount_specialized_servers(server)
    
    return server


def mount_specialized_servers(main_server: FastMCP) -> None:
    """
    Mount specialized server modules to the main server.
    
    Args:
        main_server: The main FastMCP server instance
    """
    # Create and mount specialized servers
    servers_to_mount = [
        ("coverage", create_coverage_server, "Coverage analysis and improvement tools"),
        ("testing", create_testing_server, "Test generation and enhancement tools"),
        ("security", create_security_server, "Security and compliance tools"),
        ("patterns", create_patterns_server, "Pattern matching and regex tools"),
        ("gitlab", create_gitlab_server, "GitLab CI/CD and deployment tools"),
        ("python", create_python_server, "Python development and analysis tools"),
        ("core", create_core_server, "Core development and project tools"),
        ("config", lambda: config_server, "Configuration management tools")
    ]
    
    for prefix, server_factory, description in servers_to_mount:
        try:
            specialized_server = server_factory()
            main_server.mount(specialized_server, prefix=prefix)
            print(f"✅ Mounted {prefix} server: {description}")
        except Exception as e:
            print(f"❌ Failed to mount {prefix} server: {e}")


# Create the main server instance
mcp = create_storm_mcp_server()


# Global resources available at the root level
@mcp.resource("storm-logger://server/info")
def get_server_info() -> Dict[str, Any]:
    """
    Get comprehensive server information and capabilities.
    
    Returns:
        Server information including version, capabilities, and configuration
    """
    return {
        "name": "Storm Logger Enterprise MCP Server",
        "version": STORM_MCP_VERSION,
        "description": "Enterprise-grade MCP server for Storm Logger development",
        "project_path": DEFAULT_PROJECT_PATH,
        "environment": os.getenv("STORM_MCP_ENV", "development"),
        "capabilities": {
            "coverage_analysis": "Business intelligence-driven coverage gap analysis",
            "test_generation": "Automated test generation for critical modules",
            "security_compliance": "GDPR, HIPAA, SOC2 compliance tools",
            "pattern_matching": "Intelligent regex pattern management",
            "gitlab_cicd": "Enterprise GitLab CI/CD optimization",
            "python_development": "Comprehensive Python development tools"
        },
        "business_focus": {
            "revenue_target": "$50M Storm Logger ecosystem",
            "performance_target": "6M logs/sec processing capability",
            "enterprise_readiness": "Fortune 500 adoption ready",
            "compliance_standards": ["GDPR", "HIPAA", "SOC2", "PCI-DSS"]
        },
        "tag_system": {
            "include_tags": list(mcp.include_tags) if mcp.include_tags else None,
            "exclude_tags": list(mcp.exclude_tags) if mcp.exclude_tags else None,
            "available_tags": ["public", "internal", "admin", "experimental", "stable"]
        }
    }


@mcp.resource("storm-logger://server/health")
def get_server_health() -> Dict[str, Any]:
    """
    Get server health status and diagnostics.
    
    Returns:
        Health status with diagnostics information
    """
    project_path = Path(DEFAULT_PROJECT_PATH)
    
    health_status = {
        "status": "healthy",
        "timestamp": __import__("datetime").datetime.now().isoformat(),
        "checks": {
            "project_path_exists": project_path.exists(),
            "project_path_readable": project_path.is_dir() if project_path.exists() else False,
            "environment_configured": bool(os.getenv("STORM_MCP_ENV")),
            "dependencies_available": True  # We'll assume they're available if server started
        },
        "configuration": {
            "project_path": str(project_path),
            "environment": os.getenv("STORM_MCP_ENV", "development"),
            "log_level": os.getenv("STORM_MCP_LOG_LEVEL", "INFO"),
            "mask_errors": os.getenv("STORM_MCP_MASK_ERRORS", "false").lower() == "true"
        }
    }
    
    # Overall health determination
    if not all(health_status["checks"].values()):
        health_status["status"] = "degraded"
        health_status["warnings"] = []
        
        if not health_status["checks"]["project_path_exists"]:
            health_status["warnings"].append(f"Project path {DEFAULT_PROJECT_PATH} does not exist")
        
        if not health_status["checks"]["project_path_readable"]:
            health_status["warnings"].append("Project path is not readable")
    
    return health_status


@mcp.prompt
def storm_logger_development_guide() -> str:
    """
    Comprehensive guide for Storm Logger development using the MCP server.
    
    Returns:
        Detailed development guide with examples and best practices
    """
    return """
# Storm Logger Development Guide

## 🚀 Getting Started with Storm Logger MCP Server

Welcome to the Storm Logger Enterprise MCP Server! This comprehensive guide will help you leverage all the available tools for efficient development.

### 🎯 Core Workflow

1. **Analyze Current State**
   ```
   analyze_coverage_gaps(run_coverage=True)
   ```
   
2. **Generate Missing Tests**
   ```
   generate_missing_tests(focus_area="business_critical")
   ```
   
3. **Enhance Existing Tests**
   ```
   enhance_existing_tests(test_directory="tests/")
   ```
   
4. **Track Progress**
   ```
   track_coverage_progress(target_coverage=90.0)
   ```

### 🛠️ Available Tool Categories

#### Coverage Intelligence
- `analyze_coverage_gaps` - Business impact-driven coverage analysis
- `generate_coverage_report` - Comprehensive coverage reports
- `prioritize_coverage_improvements` - Strategic improvement planning
- `track_coverage_progress` - Progress monitoring with trends

#### Test Generation & Enhancement
- `generate_missing_tests` - Automated test generation
- `enhance_existing_tests` - Test quality improvement
- `generate_test_improvement_plan` - Detailed improvement strategies

#### Security & Compliance
- `python_security_scanner` - Security vulnerability detection
- `avoid_regex_hell_create_pattern_matcher` - Secure pattern matching
- `escape_regex_hell_convert_to_pattern` - Pattern migration tools

#### Python Development
- `python_code_analyzer` - Code quality analysis
- `python_refactor_assistant` - Intelligent refactoring
- `python_documentation_generator` - Documentation generation

#### GitLab CI/CD
- `optimize_gitlabs_pipeline` - Pipeline optimization
- `implement_security_to_gitlabs_pipeline` - Security integration
- `design_deployment_for_gitlabs` - Deployment strategies

### 💡 Best Practices

1. **Start with Coverage Analysis**
   Always begin with `analyze_coverage_gaps` to understand your current state

2. **Focus on Business Impact**
   Use the business impact assessments to prioritize your work

3. **Leverage Tag System**
   Tools are tagged for easy filtering: public, internal, admin, experimental

4. **Monitor Progress**
   Regularly use `track_coverage_progress` to measure improvement

5. **Enterprise Readiness**
   All tools are designed with Fortune 500 adoption in mind

### 🏷️ Tag System

- **public**: Safe for all users
- **internal**: Internal development tools
- **admin**: Administrative functions
- **experimental**: Beta features
- **stable**: Production-ready tools

### 🔍 Troubleshooting

1. Check server health: `storm-logger://server/health`
2. Review server info: `storm-logger://server/info`
3. Verify project path configuration
4. Check environment variables (STORM_MCP_*)

### 📊 Business Intelligence Integration

This server integrates with Storm Logger's business intelligence:
- Revenue impact analysis for coverage decisions
- Enterprise readiness assessment
- Performance optimization for 6M logs/sec
- Compliance tracking for regulatory requirements

Happy coding! 🚀
"""


if __name__ == "__main__":
    # Run the enterprise MCP server
    mcp.run()