"""
GitLab CI/CD Server Module
Specialized server for GitLab CI/CD optimization and deployment tools.
"""

from typing import Dict, Optional
from fastmcp import FastMCP

# Import GitLab-related modules with flexible import handling
try:
    # Try relative imports first (when run as module)
    from ..context_logic import gitlab_operations, pipeline_optimization
except ImportError:
    # Fall back to absolute imports (when run from parent directory)
    from context_logic import gitlab_operations, pipeline_optimization


def create_gitlab_server() -> FastMCP:
    """
    Create a specialized server for GitLab CI/CD tools.
    
    Returns:
        FastMCP server instance with GitLab tools
    """
    server = FastMCP(
        name="Storm Logger GitLab CI/CD Server",
        instructions="""
        This server provides comprehensive GitLab CI/CD optimization and deployment tools 
        with enterprise-grade security and Storm Logger integration.
        """,
    )
    
    @server.tool(tags={"public", "stable"})
    def optimize_gitlabs_pipeline() -> str:
        """
        Generate optimized GitLab CI/CD pipeline configuration with Storm Logger integration
        
        Returns:
            JSON string with optimized pipeline configuration including:
            - Performance-optimized build stages
            - Storm Logger integration
            - Caching strategies
            - Parallel job execution
            - Enterprise-grade quality gates
        """
        return gitlab_operations.optimize_pipeline()
    
    @server.tool(tags={"public", "stable"})
    def implement_security_to_gitlabs_pipeline() -> str:
        """
        Generate security-focused GitLab CI/CD pipeline with comprehensive scanning and compliance
        
        Returns:
            JSON string with security pipeline configuration including:
            - Security scanning (SAST, DAST, dependency scanning)
            - Compliance checks (GDPR, HIPAA, SOC2)
            - Vulnerability management
            - Secret detection
            - Container security scanning
        """
        return gitlab_operations.implement_security_pipeline()
    
    @server.tool(tags={"public", "stable"})
    def design_deployment_for_gitlabs() -> str:
        """
        Generate deployment strategy for GitLab CI/CD with Storm Logger monitoring
        
        Returns:
            JSON string with deployment strategy configuration including:
            - Multi-environment deployment (dev, staging, prod)
            - Blue-green deployment strategies
            - Rollback procedures
            - Storm Logger integration for deployment monitoring
            - Performance monitoring and alerting
        """
        return gitlab_operations.design_deployment_strategy()
    
    @server.tool(tags={"public", "experimental"})
    def analyze_pipeline_performance(
        pipeline_config: str,
        historical_data: Optional[str] = None
    ) -> str:
        """
        Analyze GitLab pipeline performance and suggest optimizations
        
        Args:
            pipeline_config: Current pipeline configuration (YAML)
            historical_data: Historical performance data (optional)
            
        Returns:
            JSON string with performance analysis and optimization recommendations
        """
        return pipeline_optimization.analyze_pipeline_performance(
            pipeline_config, historical_data
        )
    
    @server.tool(tags={"public", "stable"})
    def generate_enterprise_pipeline_template(
        project_type: str = "python",
        security_level: str = "enterprise",
        compliance_requirements: str = "gdpr,hipaa"
    ) -> str:
        """
        Generate enterprise-grade pipeline template
        
        Args:
            project_type: Type of project (python, nodejs, java, etc.)
            security_level: Security level (basic, standard, enterprise)
            compliance_requirements: Comma-separated compliance requirements
            
        Returns:
            Complete GitLab CI/CD pipeline template with enterprise features
        """
        return gitlab_operations.generate_enterprise_template(
            project_type, security_level, compliance_requirements
        )
    
    @server.tool(tags={"public", "stable"})
    def validate_pipeline_security(
        pipeline_config: str,
        security_standards: str = "soc2,iso27001"
    ) -> str:
        """
        Validate pipeline configuration against security standards
        
        Args:
            pipeline_config: Pipeline configuration to validate
            security_standards: Security standards to validate against
            
        Returns:
            JSON string with security validation results and recommendations
        """
        return gitlab_operations.validate_pipeline_security(
            pipeline_config, security_standards
        )
    
    # Resources
    @server.resource("storm-logger://gitlab/templates")
    def get_gitlab_templates() -> str:
        """
        Get GitLab CI/CD templates for Storm Logger projects.
        
        Returns:
            JSON string with template information
        """
        return """
        {
            "gitlab_templates": {
                "basic_pipeline": {
                    "description": "Basic CI/CD pipeline with testing and building",
                    "stages": ["test", "build", "deploy"],
                    "features": ["pytest", "coverage", "docker_build"]
                },
                "enterprise_pipeline": {
                    "description": "Enterprise-grade pipeline with security and compliance",
                    "stages": ["security", "test", "build", "deploy", "monitor"],
                    "features": ["sast", "dast", "dependency_scanning", "compliance_checks"]
                },
                "storm_logger_integration": {
                    "description": "Pipeline with Storm Logger monitoring and metrics",
                    "stages": ["test", "build", "deploy", "monitor"],
                    "features": ["storm_logger_metrics", "performance_monitoring", "business_intelligence"]
                },
                "multi_environment": {
                    "description": "Multi-environment deployment pipeline",
                    "stages": ["test", "build", "deploy_dev", "deploy_staging", "deploy_prod"],
                    "features": ["environment_promotion", "rollback_procedures", "approval_gates"]
                }
            }
        }
        """
    
    @server.resource("storm-logger://gitlab/security")
    def get_gitlab_security_config() -> str:
        """
        Get GitLab security configuration recommendations.
        
        Returns:
            JSON string with security configuration
        """
        return """
        {
            "gitlab_security_config": {
                "sast": {
                    "enabled": true,
                    "tools": ["semgrep", "bandit", "safety"],
                    "fail_on": ["critical", "high"],
                    "reports": ["sast_report.json"]
                },
                "dast": {
                    "enabled": true,
                    "tools": ["zap", "nikto"],
                    "target_environments": ["staging"],
                    "fail_on": ["critical", "high"]
                },
                "dependency_scanning": {
                    "enabled": true,
                    "tools": ["gemnasium", "retire_js"],
                    "fail_on": ["critical", "high"],
                    "auto_fix": true
                },
                "secret_detection": {
                    "enabled": true,
                    "tools": ["gitleaks", "trufflecat"],
                    "fail_on": ["any"],
                    "scan_history": false
                },
                "container_scanning": {
                    "enabled": true,
                    "tools": ["clair", "trivy"],
                    "fail_on": ["critical", "high"],
                    "base_image_scanning": true
                },
                "compliance": {
                    "gdpr": {
                        "data_protection_checks": true,
                        "consent_validation": true,
                        "data_retention_checks": true
                    },
                    "hipaa": {
                        "phi_detection": true,
                        "access_control_validation": true,
                        "audit_trail_checks": true
                    },
                    "soc2": {
                        "security_controls": true,
                        "availability_checks": true,
                        "confidentiality_validation": true
                    }
                }
            }
        }
        """
    
    # Prompts
    @server.prompt
    def gitlab_optimization_strategy(
        current_pipeline: str,
        performance_goals: str = "reduce_build_time_50_percent",
        security_requirements: str = "enterprise"
    ) -> str:
        """
        Generate a comprehensive GitLab pipeline optimization strategy.
        
        Args:
            current_pipeline: Description of current pipeline setup
            performance_goals: Performance optimization goals
            security_requirements: Security requirements level
            
        Returns:
            Detailed optimization strategy
        """
        return f"""
# GitLab Pipeline Optimization Strategy

## Current State Analysis
- **Current Pipeline**: {current_pipeline}
- **Performance Goals**: {performance_goals}
- **Security Requirements**: {security_requirements}

## Optimization Approach

### Phase 1: Performance Optimization
1. **Build Time Reduction**
   - Implement aggressive caching strategies
   - Parallelize independent jobs
   - Optimize Docker layer caching
   - Use faster runners and instance types

2. **Resource Optimization**
   - Right-size runner instances
   - Implement job-specific resource allocation
   - Use spot instances for non-critical jobs
   - Optimize artifact storage and transfer

### Phase 2: Security Enhancement
1. **Security Scanning Integration**
   - SAST (Static Application Security Testing)
   - DAST (Dynamic Application Security Testing)
   - Dependency vulnerability scanning
   - Secret detection and prevention

2. **Compliance Automation**
   - GDPR compliance validation
   - HIPAA compliance checks
   - SOC2 control validation
   - Automated compliance reporting

### Phase 3: Storm Logger Integration
1. **Monitoring and Metrics**
   - Pipeline performance metrics
   - Business intelligence integration
   - Deployment success tracking
   - Error rate monitoring

2. **Business Intelligence**
   - Revenue impact analysis
   - Enterprise readiness metrics
   - Customer satisfaction tracking
   - Performance benchmarking

### Phase 4: Advanced Features
1. **Deployment Strategies**
   - Blue-green deployments
   - Canary releases
   - Feature flagging
   - Rollback automation

2. **Quality Gates**
   - Code coverage thresholds
   - Performance regression detection
   - Security vulnerability limits
   - Business metric validation

## Implementation Plan

### Week 1-2: Foundation
- Set up optimized pipeline structure
- Implement caching strategies
- Configure parallel job execution
- Basic security scanning

### Week 3-4: Security & Compliance
- Advanced security scanning
- Compliance automation
- Secret management
- Vulnerability remediation

### Week 5-6: Storm Logger Integration
- Metrics collection setup
- Business intelligence integration
- Performance monitoring
- Alert configuration

### Week 7-8: Advanced Features
- Deployment automation
- Quality gates implementation
- Performance optimization
- Documentation and training

## Success Metrics
- **Build Time**: 50% reduction in average build time
- **Security**: 100% security scan coverage
- **Compliance**: Automated compliance validation
- **Quality**: 95% deployment success rate
- **Performance**: Sub-5-minute pipeline execution

## Risk Mitigation
- Gradual rollout with feature flags
- Comprehensive testing in staging
- Rollback procedures for each change
- Performance monitoring and alerting

This strategy ensures optimal GitLab pipeline performance while maintaining enterprise-grade security and compliance standards.
"""
    
    @server.tool(tags={"health", "internal"})
    def health_check() -> Dict:
        """Health check for gitlab server."""
        import time
        
        return {
            "status": "healthy",
            "checks": {
                "server_operational": True,
                "tools_available": True
            },
            "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "server": "gitlab"
        }
    
    return server