"""
Core Development Server Module
Specialized server for core development and project management tools.
"""

from typing import Dict, Optional
from fastmcp import FastMCP

# Import core development modules with flexible import handling
try:
    # Try relative imports first (when run as module)
    from ..context_logic import project_management, development_workflow
except ImportError:
    # Fall back to absolute imports (when run from parent directory)
    from context_logic import project_management, development_workflow


def create_core_server() -> FastMCP:
    """
    Create a specialized server for core development tools.
    
    Returns:
        FastMCP server instance with core development tools
    """
    server = FastMCP(
        name="Storm Logger Core Development Server",
        instructions="""
        This server provides core development tools including project management,
        development workflow optimization, and Storm Logger specific utilities.
        """,
    )
    
    @server.tool(tags={"public", "stable"})
    def analyze_project_structure(
        project_path: str = None,
        analysis_depth: str = "comprehensive"
    ) -> str:
        """
        Analyze project structure and provide optimization recommendations
        
        Args:
            project_path: Path to the project (defaults to current directory)
            analysis_depth: Depth of analysis ("basic", "standard", "comprehensive")
            
        Returns:
            JSON string with project structure analysis and recommendations
        """
        if project_path is None:
            project_path = "/home/mathew/python-3.10.12-Projects/storm_logger"
        
        return project_management.analyze_project_structure(
            project_path, analysis_depth
        )
    
    @server.tool(tags={"public", "stable"})
    def generate_development_roadmap(
        project_goals: str = "enterprise_ready",
        timeline: str = "12_weeks",
        team_size: str = "small"
    ) -> str:
        """
        Generate comprehensive development roadmap with business intelligence focus
        
        Args:
            project_goals: Primary project goals ("enterprise_ready", "performance", "compliance", "scale")
            timeline: Timeline for roadmap ("4_weeks", "8_weeks", "12_weeks", "24_weeks")
            team_size: Team size ("small", "medium", "large")
            
        Returns:
            JSON string with detailed development roadmap and milestones
        """
        return development_workflow.generate_roadmap(
            project_goals, timeline, team_size
        )
    
    @server.tool(tags={"public", "stable"})
    def optimize_development_workflow(
        current_workflow: str = "agile",
        pain_points: list = None,
        optimization_focus: str = "productivity"
    ) -> str:
        """
        Optimize development workflow with Storm Logger integration
        
        Args:
            current_workflow: Current workflow type ("agile", "waterfall", "kanban", "custom")
            pain_points: List of current pain points
            optimization_focus: Focus area ("productivity", "quality", "speed", "collaboration")
            
        Returns:
            JSON string with workflow optimization recommendations
        """
        return development_workflow.optimize_workflow(
            current_workflow, pain_points or [], optimization_focus
        )
    
    @server.tool(tags={"public", "stable"})
    def generate_architecture_recommendations(
        current_architecture: str = "modular",
        scale_requirements: str = "enterprise",
        performance_targets: str = "6M_logs_per_sec"
    ) -> str:
        """
        Generate architecture recommendations for Storm Logger project
        
        Args:
            current_architecture: Current architecture type
            scale_requirements: Scale requirements ("startup", "growth", "enterprise")
            performance_targets: Performance targets
            
        Returns:
            JSON string with architecture recommendations and implementation plan
        """
        return project_management.generate_architecture_recommendations(
            current_architecture, scale_requirements, performance_targets
        )
    
    @server.tool(tags={"public", "experimental"})
    def create_project_template(
        template_type: str = "storm_logger_extension",
        features: list = None,
        compliance_requirements: str = "gdpr,hipaa"
    ) -> str:
        """
        Create project template with Storm Logger integration
        
        Args:
            template_type: Type of template ("storm_logger_extension", "microservice", "cli_tool")
            features: List of features to include
            compliance_requirements: Compliance requirements
            
        Returns:
            JSON string with project template code and configuration
        """
        return project_management.create_project_template(
            template_type, features or [], compliance_requirements
        )
    
    @server.tool(tags={"public", "stable"})
    def assess_technical_debt(
        project_path: str = None,
        assessment_type: str = "comprehensive",
        prioritization: str = "business_impact"
    ) -> str:
        """
        Assess technical debt and provide remediation plan
        
        Args:
            project_path: Path to the project (defaults to current directory)
            assessment_type: Type of assessment ("basic", "standard", "comprehensive")
            prioritization: Prioritization strategy ("business_impact", "complexity", "risk")
            
        Returns:
            JSON string with technical debt analysis and remediation plan
        """
        if project_path is None:
            project_path = "/home/mathew/python-3.10.12-Projects/storm_logger"
        
        return project_management.assess_technical_debt(
            project_path, assessment_type, prioritization
        )
    
    @server.tool(tags={"public", "stable"})
    def generate_quality_metrics(
        project_path: str = None,
        metrics_type: str = "comprehensive",
        business_focus: bool = True
    ) -> str:
        """
        Generate quality metrics and KPIs for Storm Logger project
        
        Args:
            project_path: Path to the project (defaults to current directory)
            metrics_type: Type of metrics ("basic", "standard", "comprehensive")
            business_focus: Whether to include business-focused metrics
            
        Returns:
            JSON string with quality metrics and improvement recommendations
        """
        if project_path is None:
            project_path = "/home/mathew/python-3.10.12-Projects/storm_logger"
        
        return project_management.generate_quality_metrics(
            project_path, metrics_type, business_focus
        )
    
    # Resources
    @server.resource("storm-logger://core/project-status")
    def get_project_status() -> str:
        """
        Get current project status and health metrics.
        
        Returns:
            JSON string with project status
        """
        return """
        {
            "project_status": {
                "version": "2.0.3",
                "health_score": 92,
                "last_updated": "2024-01-15T10:30:00Z",
                "metrics": {
                    "code_coverage": 87,
                    "test_success_rate": 98,
                    "performance_score": 94,
                    "security_score": 91,
                    "maintainability": 89
                },
                "business_metrics": {
                    "revenue_impact": "high",
                    "enterprise_readiness": 85,
                    "compliance_score": 92,
                    "customer_satisfaction": 94
                },
                "development_velocity": {
                    "commits_per_week": 15,
                    "features_delivered": 3,
                    "bugs_fixed": 8,
                    "technical_debt_ratio": 12
                }
            }
        }
        """
    
    @server.resource("storm-logger://core/development-guidelines")
    def get_development_guidelines() -> str:
        """
        Get development guidelines and best practices.
        
        Returns:
            JSON string with development guidelines
        """
        return """
        {
            "development_guidelines": {
                "code_quality": {
                    "standards": "Follow PEP 8 with 100-character line length",
                    "testing": "90% minimum code coverage",
                    "documentation": "Comprehensive docstrings for all public APIs",
                    "type_hints": "Required for all public functions and methods"
                },
                "architecture": {
                    "principles": ["Single Responsibility", "Open/Closed", "Dependency Injection"],
                    "patterns": ["Factory", "Strategy", "Observer", "Decorator"],
                    "modularity": "Keep modules focused and loosely coupled",
                    "scalability": "Design for 6M logs/sec capability"
                },
                "business_focus": {
                    "revenue_impact": "Always consider revenue impact of changes",
                    "enterprise_features": "Prioritize enterprise-grade functionality",
                    "compliance": "Ensure GDPR, HIPAA, SOC2 compliance",
                    "performance": "Maintain high-performance standards"
                },
                "workflow": {
                    "version_control": "Use semantic versioning and conventional commits",
                    "testing": "Test-driven development with comprehensive test suites",
                    "ci_cd": "Automated testing and deployment pipelines",
                    "monitoring": "Business intelligence integration for metrics"
                }
            }
        }
        """
    
    # Prompts
    @server.prompt
    def project_health_assessment(
        assessment_area: str = "comprehensive",
        business_context: str = "enterprise_growth",
        timeline: str = "quarterly"
    ) -> str:
        """
        Generate a comprehensive project health assessment prompt.
        
        Args:
            assessment_area: Area to assess ("technical", "business", "process", "comprehensive")
            business_context: Business context ("startup", "growth", "enterprise_growth", "market_leader")
            timeline: Assessment timeline ("monthly", "quarterly", "annual")
            
        Returns:
            Detailed project health assessment prompt
        """
        return f"""
# Project Health Assessment - Storm Logger

## Assessment Scope
- **Assessment Area**: {assessment_area}
- **Business Context**: {business_context}
- **Timeline**: {timeline}

## Health Assessment Framework

### 1. Technical Health
#### Code Quality Metrics
- **Code Coverage**: Target 90%+ with meaningful tests
- **Technical Debt**: Maintain debt ratio below 15%
- **Performance**: Ensure 6M logs/sec capability
- **Security**: Regular security audits and vulnerability scanning

#### Architecture Health
- **Modularity**: Assess module cohesion and coupling
- **Scalability**: Evaluate horizontal and vertical scaling
- **Maintainability**: Review code complexity and documentation
- **Extensibility**: Assess plugin and integration capabilities

### 2. Business Health
#### Revenue Impact
- **Feature Adoption**: Track enterprise feature usage
- **Customer Satisfaction**: Monitor support tickets and feedback
- **Market Position**: Assess competitive advantage
- **Revenue Growth**: Track revenue attribution to features

#### Enterprise Readiness
- **Compliance**: GDPR, HIPAA, SOC2 compliance status
- **Security**: Enterprise-grade security posture
- **Scalability**: Fortune 500 deployment readiness
- **Support**: Enterprise support capabilities

### 3. Process Health
#### Development Velocity
- **Feature Delivery**: Track feature delivery rate
- **Bug Resolution**: Monitor bug fix velocity
- **Technical Debt**: Assess debt accumulation rate
- **Team Productivity**: Measure developer productivity

#### Quality Assurance
- **Testing Coverage**: Comprehensive test coverage
- **Automation**: CI/CD pipeline effectiveness
- **Monitoring**: Business intelligence integration
- **Feedback Loops**: Customer feedback integration

### 4. Strategic Health
#### Business Alignment
- **Goal Achievement**: Progress toward $50M revenue target
- **Market Expansion**: Enterprise market penetration
- **Innovation**: New feature development pipeline
- **Competitive Advantage**: Unique value proposition strength

#### Risk Management
- **Technical Risks**: Identify and mitigate technical risks
- **Business Risks**: Assess market and competitive risks
- **Operational Risks**: Evaluate operational dependencies
- **Compliance Risks**: Monitor regulatory compliance

## Assessment Methodology

### Data Collection
1. **Automated Metrics**: Use Storm Logger's business intelligence
2. **Code Analysis**: Comprehensive code quality analysis
3. **Performance Benchmarks**: Regular performance testing
4. **Security Scans**: Automated and manual security assessments

### Analysis Framework
1. **Trend Analysis**: Compare current vs. historical performance
2. **Benchmark Comparison**: Industry and internal benchmarks
3. **Impact Assessment**: Business impact of identified issues
4. **Risk Prioritization**: Prioritize issues by business impact

### Reporting
1. **Executive Summary**: High-level health status
2. **Detailed Analysis**: Technical and business deep dive
3. **Action Plan**: Prioritized improvement recommendations
4. **Success Metrics**: KPIs for monitoring progress

## Success Criteria
- **Technical**: 95%+ code quality score
- **Business**: 90%+ customer satisfaction
- **Process**: 80%+ development velocity
- **Strategic**: On track for business goals

This assessment ensures Storm Logger maintains its position as the leading enterprise logging solution while supporting the $50M revenue ecosystem.
"""
    
    @server.tool(tags={"health", "internal"})
    def health_check() -> Dict:
        """Health check for core server."""
        import time
        
        checks = {
            "server_operational": True,
            "tools_available": True,
            "project_management_module": False,
            "development_workflow_module": False
        }
        
        # Test context logic modules with multiple import strategies
        # Try relative imports first
        try:
            from ..context_logic import project_management
            checks["project_management_module"] = True
            checks["project_management_functions"] = len([attr for attr in dir(project_management) if not attr.startswith('_') and callable(getattr(project_management, attr))])
        except ImportError:
            # Try absolute import
            try:
                from _mcp.context_logic import project_management
                checks["project_management_module"] = True
                checks["project_management_functions"] = len([attr for attr in dir(project_management) if not attr.startswith('_') and callable(getattr(project_management, attr))])
            except ImportError:
                # Try from context_logic directly
                try:
                    from context_logic import project_management
                    checks["project_management_module"] = True
                    checks["project_management_functions"] = len([attr for attr in dir(project_management) if not attr.startswith('_') and callable(getattr(project_management, attr))])
                except ImportError:
                    checks["project_management_module"] = False
        
        # Similar approach for development_workflow
        try:
            from ..context_logic import development_workflow
            checks["development_workflow_module"] = True
            checks["development_workflow_functions"] = len([attr for attr in dir(development_workflow) if not attr.startswith('_') and callable(getattr(development_workflow, attr))])
        except ImportError:
            try:
                from _mcp.context_logic import development_workflow
                checks["development_workflow_module"] = True
                checks["development_workflow_functions"] = len([attr for attr in dir(development_workflow) if not attr.startswith('_') and callable(getattr(development_workflow, attr))])
            except ImportError:
                try:
                    from context_logic import development_workflow
                    checks["development_workflow_module"] = True
                    checks["development_workflow_functions"] = len([attr for attr in dir(development_workflow) if not attr.startswith('_') and callable(getattr(development_workflow, attr))])
                except ImportError:
                    checks["development_workflow_module"] = False
        
        # Determine overall health status
        critical_checks = ["server_operational", "tools_available"]
        all_critical_pass = all(checks[check] for check in critical_checks)
        
        if all(checks.values()):
            status = "healthy"
        elif all_critical_pass:
            status = "warning"
        else:
            status = "error"
        
        return {
            "status": status,
            "checks": checks,
            "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "server": "core"
        }
    
    return server