"""
Python Development Server Module
Specialized server for Python development and analysis tools.
"""

from typing import Dict, Optional
from fastmcp import FastMCP
import json

# Import Python development modules with flexible import handling
try:
    # Try relative imports first (when run as module)
    from ..context_logic import (
        python_analysis, 
        python_refactoring,
        code_refactoring, 
        documentation_generation,
        python_test_generation,
        python_dependencies
    )
except ImportError:
    # Fall back to absolute imports (when run from parent directory)
    from context_logic import (
        python_analysis,
        python_refactoring, 
        code_refactoring, 
        documentation_generation,
        python_test_generation,
        python_dependencies
    )


def create_python_server() -> FastMCP:
    """
    Create a specialized server for Python development tools.
    
    Returns:
        FastMCP server instance with Python development tools
    """
    server = FastMCP(
        name="Storm Logger Python Development Server",
        instructions="""
        This server provides comprehensive Python development tools including 
        code analysis, refactoring, documentation, and dependency management.
        
        IMPORTANT: Access the PathLib guidance resource at storm-logger://python/pathlib-guidance
        for critical learnings about Path('') behavior and common pitfalls discovered
        during Storm Logger development.
        """,
    )
    
    @server.tool(tags={"public", "stable"})
    def python_code_analyzer(
        file_path: str,
        analysis_type: str = "comprehensive",
        include_storm_logger: bool = True
    ) -> str:
        """
        Comprehensive Python code analysis tool for quality, security, and Storm Logger compliance
        
        Args:
            file_path: Path to Python file or directory to analyze
            analysis_type: Type of analysis ("quality", "security", "performance", "storm_logger", "comprehensive")
            include_storm_logger: Whether to include Storm Logger specific analysis
            
        Returns:
            JSON string with detailed analysis results and recommendations
        """
        return python_analysis.analyze_code(
            file_path, analysis_type, include_storm_logger
        )
    
    @server.tool(tags={"public", "stable"})
    def python_refactor_assistant(
        file_path: str,
        refactor_type: str = "comprehensive",
        safety_level: str = "moderate",
        apply_changes: bool = False
    ) -> str:
        """
        Intelligent Python refactoring assistant with Storm Logger best practices
        
        Args:
            file_path: Path to Python file or directory to refactor
            refactor_type: Type of refactoring ("modernize", "extract", "optimize", "type_hints", "comprehensive")
            safety_level: Safety level for refactoring ("conservative", "moderate", "aggressive")
            apply_changes: Whether to apply changes or just preview
            
        Returns:
            JSON string with refactoring suggestions and applied changes
        """
        return code_refactoring.refactor_code(
            file_path, refactor_type, safety_level, apply_changes
        )
    
    @server.tool(tags={"public", "stable"})
    def python_test_generator(
        file_path: str,
        test_type: str = "unit",
        coverage_target: int = 90,
        test_framework: str = "pytest"
    ) -> str:
        """
        Generate comprehensive Python test suites with Storm Logger integration
        
        Args:
            file_path: Path to Python file to generate tests for
            test_type: Type of tests ("unit", "integration", "functional", "performance", "comprehensive")
            coverage_target: Target coverage percentage (90-100)
            test_framework: Test framework to use ("pytest", "unittest", "doctest")
            
        Returns:
            JSON string with generated test code, fixtures, and coverage analysis
        """
        return python_test_generation.generate_tests(
            file_path, test_type, coverage_target, test_framework
        )
    
    @server.tool(tags={"public", "stable"})
    def python_documentation_generator(
        file_path: str,
        doc_type: str = "comprehensive",
        output_format: str = "markdown",
        include_examples: bool = True
    ) -> str:
        """
        Generate comprehensive documentation for Python code with Storm Logger integration
        
        Args:
            file_path: Path to Python file or directory to document
            doc_type: Type of documentation ("api", "readme", "docstrings", "changelog", "comprehensive")
            output_format: Output format ("markdown", "rst", "html", "json")
            include_examples: Whether to include code examples
            
        Returns:
            JSON string with generated documentation, quality analysis, and recommendations
        """
        return documentation_generation.generate_documentation(
            file_path, doc_type, output_format, include_examples
        )
    
    @server.tool(tags={"public", "stable"})
    def python_dependency_manager(
        project_path: str,
        operation: str = "analyze",
        update_strategy: str = "conservative",
        security_scan: bool = True
    ) -> str:
        """
        Comprehensive dependency management with security scanning and update recommendations
        
        Args:
            project_path: Path to Python project directory
            operation: Operation type ("analyze", "update", "security_scan", "cleanup", "comprehensive")
            update_strategy: Update strategy ("conservative", "moderate", "aggressive")
            security_scan: Whether to perform security vulnerability scanning
            
        Returns:
            JSON string with dependency analysis, vulnerabilities, and recommendations
        """
        return python_dependencies.manage_dependencies(
            project_path, operation, update_strategy, security_scan
        )
    
    @server.tool(tags={"public", "experimental"})
    def python_performance_profiler(
        file_path: str,
        profiling_type: str = "comprehensive",
        optimization_focus: str = "speed"
    ) -> str:
        """
        Profile Python code performance and suggest optimizations
        
        Args:
            file_path: Path to Python file to profile
            profiling_type: Type of profiling ("cpu", "memory", "io", "comprehensive")
            optimization_focus: Focus area ("speed", "memory", "scalability")
            
        Returns:
            JSON string with performance analysis and optimization recommendations
        """
        # TODO: Implement profile_performance function
        return json.dumps({
            "status": "error",
            "message": "Performance profiling not yet implemented"
        })
    
    @server.tool(tags={"public", "stable"})
    def python_type_hint_generator(
        file_path: str,
        coverage_level: str = "comprehensive",
        include_return_types: bool = True
    ) -> str:
        """
        Generate type hints for Python code with Storm Logger compatibility
        
        Args:
            file_path: Path to Python file to add type hints to
            coverage_level: Coverage level ("basic", "standard", "comprehensive")
            include_return_types: Whether to include return type hints
            
        Returns:
            JSON string with type hint suggestions and updated code
        """
        return code_refactoring.generate_type_hints(
            file_path, coverage_level, include_return_types
        )
    
    # Resources
    @server.resource("storm-logger://python/standards")
    def get_python_standards() -> str:
        """
        Get Python development standards and best practices for Storm Logger.
        
        Returns:
            JSON string with development standards
        """
        return """
        {
            "python_standards": {
                "code_style": {
                    "formatter": "black",
                    "line_length": 100,
                    "import_sorting": "isort",
                    "linting": "ruff",
                    "type_checking": "mypy"
                },
                "naming_conventions": {
                    "classes": "PascalCase",
                    "functions": "snake_case",
                    "variables": "snake_case",
                    "constants": "UPPER_CASE",
                    "modules": "snake_case"
                },
                "documentation": {
                    "docstring_style": "google",
                    "coverage_requirement": "100% for public APIs",
                    "examples_required": "Yes for complex functions",
                    "type_hints_required": "Yes for all public APIs"
                },
                "testing": {
                    "framework": "pytest",
                    "coverage_target": "90% minimum",
                    "test_categories": ["unit", "integration", "functional", "performance"],
                    "fixtures": "Use Storm Logger test fixtures"
                },
                "performance": {
                    "profiling": "Required for critical paths",
                    "benchmarking": "Performance regression testing",
                    "optimization": "Focus on 6M logs/sec capability",
                    "monitoring": "Business intelligence integration"
                }
            }
        }
        """
    
    @server.resource("storm-logger://python/patterns")
    def get_python_patterns() -> str:
        """
        Get Python design patterns and Storm Logger integration patterns.
        
        Returns:
            JSON string with pattern information
        """
        return """
        {
            "python_patterns": {
                "storm_logger_patterns": {
                    "logger_creation": "Use ProfessionalStormLogger for enterprise features",
                    "configuration": "Use dataclass-based configuration patterns",
                    "error_handling": "Integrate with Storm Logger error tracking",
                    "performance_tracking": "Use Storm Logger metrics for performance monitoring"
                },
                "design_patterns": {
                    "singleton": "Use for global instances (metrics, console)",
                    "factory": "Use for logger creation based on framework",
                    "strategy": "Use for configurable formatters and handlers",
                    "observer": "Use for event-based logging hooks",
                    "decorator": "Use for performance tracking and logging"
                },
                "enterprise_patterns": {
                    "dependency_injection": "Use for testable, maintainable code",
                    "configuration_management": "Environment-based configuration",
                    "error_handling": "Comprehensive error handling with logging",
                    "monitoring": "Business intelligence integration"
                },
                "performance_patterns": {
                    "lazy_evaluation": "For expensive operations",
                    "caching": "For repeated computations",
                    "batch_processing": "For I/O operations",
                    "async_support": "For high-concurrency scenarios"
                }
            }
        }
        """
    
    @server.resource("storm-logger://python/pathlib-guidance")
    def get_pathlib_guidance() -> str:
        """
        Get PathLib best practices and common pitfalls for Storm Logger development.
        
        Returns:
            JSON string with PathLib guidance and lessons learned
        """
        return """
        {
            "pathlib_guidance": {
                "critical_learnings": {
                    "empty_string_behavior": {
                        "issue": "Path('') becomes Path('.'), not an empty path",
                        "example": "Path('') == Path('.')  # True",
                        "impact": "str(Path('')) returns '.' not ''",
                        "testing": "Always test empty string paths explicitly"
                    },
                    "falsy_check_pitfall": {
                        "issue": "Empty string is falsy but Path('.') is truthy",
                        "wrong": "if self.archive_directory and isinstance(self.archive_directory, str)",
                        "correct": "if isinstance(self.archive_directory, str) and self.archive_directory",
                        "result": "Empty string paths may not be normalized as expected"
                    },
                    "none_handling": {
                        "issue": "Path(None) raises TypeError",
                        "solution": "Always check for None before creating Path",
                        "pattern": "Path(value) if value is not None else None"
                    }
                },
                "best_practices": {
                    "normalization_pattern": {
                        "description": "Safe path normalization with explicit empty string handling",
                        "code": [
                            "def normalize_path(path_value):",
                            "    if path_value is None:",
                            "        return None",
                            "    if isinstance(path_value, Path):",
                            "        return path_value",
                            "    if isinstance(path_value, str):",
                            "        if not path_value:  # Empty string",
                            "            return None  # or Path('.') based on use case",
                            "        return Path(path_value)",
                            "    raise TypeError(f'Expected str or Path, got {type(path_value)}')"
                        ]
                    },
                    "testing_paths": {
                        "test_cases": [
                            "Path('') - becomes current directory",
                            "Path('.') - current directory",
                            "Path(None) - raises TypeError",
                            "Path('/absolute') - absolute path",
                            "Path('relative') - relative path"
                        ],
                        "assertions": [
                            "assert Path('') == Path('.')",
                            "assert str(Path('')) == '.'",
                            "assert Path('.').exists()",
                            "assert not Path('relative').is_absolute()"
                        ]
                    }
                },
                "storm_logger_specific": {
                    "config_normalization": {
                        "issue": "StormLoggerConfig path normalization has falsy check",
                        "behavior": "Empty string archive_directory is NOT normalized",
                        "code_location": "storm_logger/config.py:_normalize_paths()",
                        "workaround": "Explicitly handle empty strings in config"
                    },
                    "dependency_injection": {
                        "pattern": "Use FileSystemOps abstraction for testability",
                        "benefit": "Allows mocking path operations in tests",
                        "example": "MockFileSystemOps in test_config_refactored.py"
                    }
                },
                "common_operations": {
                    "path_components": {
                        "name": "path.name - filename with extension",
                        "stem": "path.stem - filename without extension",
                        "suffix": "path.suffix - file extension",
                        "parent": "path.parent - parent directory",
                        "parents": "path.parents - all parent directories"
                    },
                    "path_manipulation": {
                        "with_suffix": "path.with_suffix('.txt') - change extension",
                        "with_name": "path.with_name('new.log') - change filename",
                        "joinpath": "path / 'subdir' / 'file.txt' - join paths",
                        "resolve": "path.resolve() - absolute path with symlinks resolved"
                    },
                    "file_operations": {
                        "exists": "path.exists() - check if exists",
                        "is_file": "path.is_file() - check if regular file",
                        "is_dir": "path.is_dir() - check if directory",
                        "mkdir": "path.mkdir(parents=True, exist_ok=True)",
                        "touch": "path.touch() - create empty file",
                        "unlink": "path.unlink() - delete file"
                    }
                },
                "references": {
                    "detailed_guide": "_mcp/resources/pathlib_guidance.md",
                    "storm_logger_claude": "CLAUDE.md - PathLib Best Practices section",
                    "test_examples": "tests/unit/test_config_missing_branches.py"
                }
            }
        }
        """
    
    # Prompts
    @server.prompt
    def python_modernization_strategy(
        current_version: str,
        target_version: str = "3.12",
        codebase_size: str = "medium",
        business_impact: str = "high"
    ) -> str:
        """
        Generate a comprehensive Python modernization strategy.
        
        Args:
            current_version: Current Python version
            target_version: Target Python version
            codebase_size: Size of codebase (small, medium, large)
            business_impact: Business impact level (low, medium, high, critical)
            
        Returns:
            Detailed modernization strategy
        """
        return f"""
# Python Modernization Strategy

## Current State Analysis
- **Current Version**: Python {current_version}
- **Target Version**: Python {target_version}
- **Codebase Size**: {codebase_size}
- **Business Impact**: {business_impact}

## Modernization Approach

### Phase 1: Compatibility Assessment
1. **Dependency Analysis**
   - Audit all dependencies for Python {target_version} compatibility
   - Identify deprecated features and removed functionality
   - Assess third-party library support
   - Plan dependency updates and replacements

2. **Code Analysis**
   - Use `python_code_analyzer` for comprehensive code analysis
   - Identify syntax incompatibilities
   - Locate deprecated standard library usage
   - Assess performance optimization opportunities

### Phase 2: Incremental Migration
1. **Syntax Modernization**
   - Update f-strings and string formatting
   - Modernize type hints with new syntax
   - Use match statements where appropriate
   - Implement positional-only and keyword-only parameters

2. **Standard Library Updates**
   - Replace deprecated modules and functions
   - Use new standard library features
   - Optimize imports and module usage
   - Implement new error handling patterns

### Phase 3: Performance Optimization
1. **Language Feature Utilization**
   - Leverage improved dictionary performance
   - Use new asyncio features for concurrency
   - Implement structural pattern matching
   - Optimize with new built-in functions

2. **Storm Logger Integration**
   - Ensure Storm Logger compatibility
   - Optimize logging performance
   - Integrate with business intelligence features
   - Maintain enterprise-grade functionality

### Phase 4: Testing and Validation
1. **Comprehensive Testing**
   - Use `python_test_generator` for test coverage
   - Implement performance regression tests
   - Validate enterprise features
   - Test Storm Logger integration

2. **Business Validation**
   - Ensure 6M logs/sec capability
   - Validate enterprise readiness
   - Test compliance requirements
   - Verify revenue-critical functionality

## Risk Mitigation

### Technical Risks
- **Compatibility Issues**: Comprehensive testing in staging
- **Performance Regression**: Continuous benchmarking
- **Dependency Conflicts**: Careful dependency management
- **Breaking Changes**: Gradual rollout with feature flags

### Business Risks
- **Revenue Impact**: Parallel deployment strategies
- **Enterprise Customers**: Extensive validation testing
- **Compliance Requirements**: Regulatory compliance verification
- **Support Burden**: Comprehensive documentation and training

## Success Metrics
- **Performance**: 20% improvement in execution speed
- **Security**: Enhanced security with latest Python features
- **Maintainability**: 30% reduction in technical debt
- **Developer Experience**: Improved productivity and code quality

## Implementation Timeline
- **Phase 1**: 2 weeks - Assessment and planning
- **Phase 2**: 4 weeks - Incremental migration
- **Phase 3**: 2 weeks - Performance optimization
- **Phase 4**: 2 weeks - Testing and validation

This strategy ensures a smooth transition to Python {target_version} while maintaining Storm Logger's enterprise-grade quality and business intelligence capabilities.
"""
    
    @server.prompt
    def pathlib_safe_config_implementation(
        config_class_name: str = "StormLoggerConfig",
        path_fields: str = "log_directory,archive_directory,temp_directory",
        allow_empty_strings: bool = False
    ) -> str:
        """
        Generate PathLib-safe configuration implementation avoiding common pitfalls.
        
        Args:
            config_class_name: Name of the configuration class
            path_fields: Comma-separated list of path field names
            allow_empty_strings: Whether to allow empty string paths
            
        Returns:
            Safe configuration implementation with proper path handling
        """
        fields = [f.strip() for f in path_fields.split(',')]
        
        # Helper for conditional returns
        empty_string_return = "return None  # Explicitly handle empty strings" if not allow_empty_strings else "return Path('.')  # Empty string becomes current directory"
        empty_string_return2 = "return None  # Don't create Path from empty string" if not allow_empty_strings else "return Path('.')  # Current directory"
        empty_test_result = "is None" if not allow_empty_strings else "== Path('.')"
        
        # Build field definitions
        field_defs = '\n'.join(f'    {field}: Optional[Path] = None' for field in fields)
        
        # Build post_init normalizations
        normalizations = '\n'.join(f'        self.{field} = self._normalize_{field}()' for field in fields)
        
        # Build normalize methods
        normalize_methods = []
        for field in fields:
            method = f'''    def _normalize_{field}(self) -> Optional[Path]:
        """Normalize {field} with safe empty string handling."""
        if self.{field} is None:
            return None
        
        if isinstance(self.{field}, Path):
            return self.{field}
        
        if isinstance(self.{field}, str):
            if not self.{field}:  # Empty string check
                {empty_string_return2}
            return Path(self.{field})
        
        return self.{field}
'''
            normalize_methods.append(method)
        
        # Build test assertions  
        test_assertions = '\n'.join(f'        assert config.{field} {empty_test_result}  # Empty string handled correctly' for field in fields[:2])
        test_empty_params = '\n'.join(f'            {field}="",' for field in fields[:2])
        test_none_assertions = '\n'.join(f'        assert config.{field} is None' for field in fields)
        test_path_params = '\n'.join(f'            "{field}": Path("/test/{field}"),' for field in fields)
        test_path_assertions = '\n'.join(f'        assert config.{field} == Path("/test/{field}")' for field in fields)
        test_str_params = '\n'.join(f'            {field}="/test/{field}",' for field in fields[:2])
        test_str_assertions1 = '\n'.join(f'        assert isinstance(config.{field}, Path)' for field in fields[:2])
        test_str_assertions2 = '\n'.join(f'        assert str(config.{field}) == "/test/{field}"' for field in fields[:2])
        
        return f'''
# PathLib-Safe Configuration Implementation for {config_class_name}

## Critical PathLib Learnings Applied

### 1. Empty String Handling
Remember: `Path('')` becomes `Path('.')` (current directory), NOT an empty path!

### 2. Safe Path Normalization Pattern

```python
from pathlib import Path
from typing import Optional, Union
from dataclasses import dataclass, field

def normalize_path(value: Union[str, Path, None]) -> Optional[Path]:
    """Safely normalize path values with explicit empty string handling.
    
    Critical: Path('') == Path('.') - empty strings become current directory!
    """
    if value is None:
        return None
    
    if isinstance(value, Path):
        return value
    
    if isinstance(value, str):
        if not value:  # Empty string
            {empty_string_return}
        return Path(value)
    
    raise TypeError(f"Expected str, Path, or None; got {{type(value)}}")


@dataclass
class {config_class_name}:
    """Configuration with PathLib-safe path handling."""
    
{field_defs}
    
    # Dependencies for testability
    _fs_ops: Optional["FileSystemOps"] = field(default=None, init=False, repr=False)
    
    def __post_init__(self):
        """Normalize paths with explicit empty string handling."""
        # Initialize filesystem operations
        if self._fs_ops is None:
            self._fs_ops = RealFileSystemOps()
        
        # Normalize each path field
{normalizations}
    
{''.join(normalize_methods)}

### 3. Testing Path Normalization

```python
import pytest
from pathlib import Path

class Test{config_class_name}Paths:
    """Test path normalization edge cases."""
    
    def test_empty_string_paths(self):
        """Test that empty strings are handled correctly."""
        config = {config_class_name}(
{test_empty_params}
        )
        
        # Verify empty strings are handled as intended
{test_assertions}
    
    def test_none_paths(self):
        """Test that None values remain None."""
        config = {config_class_name}()  # All default to None
        
{test_none_assertions}
    
    def test_path_object_preservation(self):
        """Test that Path objects are preserved."""
        paths = {{
{test_path_params}
        }}
        config = {config_class_name}(**paths)
        
{test_path_assertions}
    
    def test_string_to_path_conversion(self):
        """Test normal string to Path conversion."""
        config = {config_class_name}(
{test_str_params}
        )
        
{test_str_assertions1}
{test_str_assertions2}
```

### 4. Common Pitfalls to Avoid

```python
# WRONG - Falsy check before type check
if self.archive_directory and isinstance(self.archive_directory, str):
    self.archive_directory = Path(self.archive_directory)
# Result: Empty string remains as empty string!

# CORRECT - Type check first, then falsy check
if isinstance(self.archive_directory, str):
    if self.archive_directory:  # Only convert non-empty
        self.archive_directory = Path(self.archive_directory)
    else:
        self.archive_directory = None  # Explicit handling

# WRONG - Not handling Path(None) TypeError
self.path = Path(self.path)  # Raises TypeError if None!

# CORRECT - Check for None first
self.path = Path(self.path) if self.path is not None else None
```

### 5. FileSystemOps Pattern for Testability

```python
from abc import ABC, abstractmethod

class FileSystemOps(ABC):
    """Abstract interface for file system operations."""
    
    @abstractmethod
    def mkdir(self, path: Path, parents: bool = False, exist_ok: bool = False) -> None:
        pass
    
    @abstractmethod
    def exists(self, path: Path) -> bool:
        pass

class RealFileSystemOps(FileSystemOps):
    """Real file system operations."""
    
    def mkdir(self, path: Path, parents: bool = False, exist_ok: bool = False) -> None:
        path.mkdir(parents=parents, exist_ok=exist_ok)
    
    def exists(self, path: Path) -> bool:
        return path.exists()

class MockFileSystemOps(FileSystemOps):
    """Mock for testing."""
    
    def __init__(self):
        self.created_paths = []
        self.existing_paths = set()
    
    def mkdir(self, path: Path, parents: bool = False, exist_ok: bool = False) -> None:
        self.created_paths.append((path, parents, exist_ok))
        self.existing_paths.add(str(path))
    
    def exists(self, path: Path) -> bool:
        return str(path) in self.existing_paths
```

## Key Takeaways

1. **Always** handle empty strings explicitly - they become `Path('.')`
2. **Never** use falsy checks before type checks for path normalization
3. **Always** check for None before passing to Path()
4. **Test** empty strings, None, and Path objects explicitly
5. **Use** dependency injection for filesystem operations

This implementation ensures safe path handling and avoids the PathLib pitfalls discovered during Storm Logger development.
'''
    
    @server.tool(tags={"health", "internal"})
    def health_check() -> Dict:
        """Health check for python 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": "python"
        }
    
    return server