"""
Workflow optimization and prompt generation logic
"""

from typing import Dict, Any, List


def debug_test_failure(failing_test: str, error_output: str, recent_changes: str = "") -> str:
    """
    Generate comprehensive debugging prompt for test failures
    
    Args:
        failing_test: Name of the failing test
        error_output: Full error output from the test
        recent_changes: Recent changes made (optional)
        
    Returns:
        Debugging prompt text
    """
    prompt = f"""
# Storm Logger Test Failure Debugging

## Failing Test Analysis
**Test Name:** {failing_test}
**Recent Changes:** {recent_changes if recent_changes else "None specified"}

## Error Output
```
{error_output}
```

## Debugging Strategy

### 1. Immediate Actions
- Run the specific test in isolation: `./test.sh -k {failing_test} -v`
- Check if this is a new failure or regression
- Verify the test was working before recent changes

### 2. Common Storm Logger Patterns to Check
- **Console Methods:** Parameter order issues (title, columns, rows vs columns, rows, title=...)
- **Import Errors:** Missing dependencies or circular imports
- **Configuration:** Django settings or standalone configuration issues
- **Business Logic:** Metrics collection or sanitization failures

### 3. Analysis Framework
Based on the error output above, investigate:
- What type of error is this? (ImportError, AttributeError, TypeError, AssertionError)
- Which Storm Logger component is involved? (console, logger, config, integrations)
- Is this a unit test, integration test, or functional test?
- Are there similar working tests to compare against?

### 4. Storm Logger Specific Debugging
- Check if the test uses proper Storm Logger fixtures
- Verify mock configurations match actual implementations
- Look for recent changes in the tested component
- Check if test dependencies are properly set up

### 5. Next Steps
1. Run the test with maximum verbosity: `./test.sh -k {failing_test} -vvv`
2. Check related tests: `./test.sh -k similar_pattern --quick`
3. Look at working tests for the same component
4. Check Storm Logger documentation for the failing component
5. Consider if the test needs updating due to recent changes

### 6. Storm Logger Context
This analysis should consider:
- Business intelligence features impact
- Professional logging requirements
- Enterprise-grade reliability expectations
- Framework integration specifics (Django, Flask, etc.)

Generate a specific debugging plan based on the error pattern and Storm Logger architecture.
"""
    return prompt


def implement_test_script_feature(feature_description: str, current_script_capabilities: str, user_workflow: str) -> str:
    """
    Generate implementation prompt for new test script features
    
    Args:
        feature_description: Description of the desired feature
        current_script_capabilities: Current script capabilities
        user_workflow: User's current workflow
        
    Returns:
        Implementation prompt text
    """
    prompt = f"""
# Storm Test Script Feature Implementation

## Feature Request
**Desired Feature:** {feature_description}
**Current Capabilities:** {current_script_capabilities}
**User Workflow:** {user_workflow}

## Implementation Strategy

### 1. Feature Analysis
Analyze the requested feature:
- What problem does it solve?
- How does it fit into the Storm Logger testing philosophy?
- What are the technical requirements?
- How will it improve the developer experience?

### 2. Storm Script Architecture
The Storm test script follows these principles:
- **Simplicity:** Easy to use and understand
- **Power:** Supports advanced testing scenarios
- **Integration:** Works with pytest and Storm Logger
- **Branding:** Maintains Storm Logger identity and experience

### 3. Implementation Approach
Consider these implementation strategies:
- **Option Parsing:** Add new command-line options with clear help text
- **Backward Compatibility:** Ensure existing workflows continue to work
- **Error Handling:** Provide clear error messages and fallbacks
- **Performance:** Minimize impact on test execution speed

### 4. Code Structure
Follow Storm script patterns:
- Use clear bash functions for complex logic
- Add comprehensive help documentation
- Include usage examples
- Maintain consistent option naming

### 5. Testing Strategy
Ensure the new feature:
- Works across different environments
- Handles edge cases gracefully
- Maintains script reliability
- Provides clear user feedback

### 6. Integration Points
Consider integration with:
- **pytest:** Native pytest options and plugins
- **Storm Logger:** Business metrics and professional output
- **CI/CD:** GitLab CI and other automation
- **Development Tools:** IDEs and text editors

### 7. User Experience
Focus on:
- **Discoverability:** Easy to find and understand
- **Consistency:** Follows existing patterns
- **Feedback:** Clear progress and result indicators
- **Documentation:** Comprehensive help and examples

## Implementation Plan

Generate a detailed implementation plan that includes:
1. **Option Definition:** Command-line option syntax and behavior
2. **Code Structure:** Bash functions and logic organization
3. **Error Handling:** Edge cases and error scenarios
4. **Testing:** How to test the new feature
5. **Documentation:** Help text and usage examples
6. **Rollout:** Gradual introduction and user feedback

Consider the Storm Logger enterprise context and the need for professional, reliable tooling.
"""
    return prompt


def optimize_testing_workflow(current_workflow: str, pain_points: List[str], team_size: str = "small") -> str:
    """
    Generate workflow optimization prompt
    
    Args:
        current_workflow: Description of current workflow
        pain_points: List of identified pain points
        team_size: Size of the team (small, medium, large)
        
    Returns:
        Workflow optimization prompt text
    """
    prompt = f"""
# Storm Logger Testing Workflow Optimization

## Current State Analysis
**Current Workflow:** {current_workflow}
**Team Size:** {team_size}
**Pain Points:** {', '.join(pain_points)}

## Optimization Strategy

### 1. Workflow Assessment
Analyze the current testing workflow:
- What are the bottlenecks?
- Where do developers spend the most time?
- Which steps are manual and could be automated?
- What causes the most frustration?

### 2. Storm Logger Testing Philosophy
Align with Storm Logger principles:
- **Business Intelligence:** Testing should provide business insights
- **Professional Quality:** Enterprise-grade reliability and reporting
- **Developer Experience:** Smooth, efficient development workflow
- **Continuous Improvement:** Regular optimization and enhancement

### 3. Optimization Areas

#### Performance Optimization
- **Test Execution Speed:** Parallel execution, selective testing
- **Feedback Loop:** Faster failure detection and reporting
- **Resource Usage:** Efficient memory and CPU utilization
- **Caching:** Reuse of test data and fixtures

#### Process Optimization
- **Test Selection:** Smart filtering and targeting
- **Debugging:** Efficient failure analysis and resolution
- **Reporting:** Clear, actionable test results
- **Integration:** Seamless CI/CD integration

#### Team Optimization
- **Collaboration:** Shared testing practices and standards
- **Knowledge Sharing:** Documentation and training
- **Consistency:** Standardized testing approaches
- **Scalability:** Processes that grow with the team

### 4. Technology Integration
Leverage Storm Logger features:
- **Rich Console Output:** Better test result visualization
- **Business Metrics:** Track testing efficiency and quality
- **Professional Logging:** Comprehensive test execution logs
- **Framework Integration:** Django, Flask, and standalone support

### 5. Team-Specific Considerations

#### Small Team ({team_size})
- Focus on automation and efficiency
- Minimize manual processes
- Quick feedback loops
- Shared responsibility for test quality

#### Medium Team
- Standardized processes and tools
- Clear ownership and responsibilities
- Automated quality gates
- Regular workflow reviews

#### Large Team
- Scalable processes and infrastructure
- Comprehensive reporting and analytics
- Specialized testing roles
- Enterprise-grade tooling

### 6. Implementation Roadmap

#### Phase 1: Quick Wins (1-2 weeks)
- Address most painful manual processes
- Implement basic automation
- Improve test execution speed
- Add better error reporting

#### Phase 2: Process Improvements (1-2 months)
- Standardize testing practices
- Implement advanced filtering
- Add comprehensive reporting
- Integrate with CI/CD

#### Phase 3: Advanced Optimization (3-6 months)
- Advanced analytics and insights
- Predictive testing strategies
- Machine learning integration
- Enterprise-grade features

### 7. Success Metrics
Track optimization success:
- **Test Execution Time:** Reduce overall testing time
- **Developer Satisfaction:** Improved workflow experience
- **Bug Detection Rate:** Earlier and more effective bug finding
- **Release Confidence:** Higher confidence in releases

## Optimization Recommendations

Generate specific recommendations for:
1. **Immediate Actions:** Quick wins that can be implemented right away
2. **Process Changes:** Workflow modifications for better efficiency
3. **Tool Enhancements:** Improvements to the Storm test script
4. **Team Practices:** Changes in team testing practices
5. **Long-term Strategy:** Vision for the future testing workflow

Consider the Storm Logger enterprise context and the goal of $10M revenue through superior software quality.
"""
    return prompt


def generate_storm_logger_test_plan(feature: str) -> str:
    """
    Generate test plan prompt for Storm Logger features
    
    Args:
        feature: Feature to create test plan for
        
    Returns:
        Test plan prompt text
    """
    prompt = f"""
# Storm Logger Test Plan: {feature}

## Test Strategy Framework

### 1. Business Context
**Feature:** {feature}
**Business Value:** How does this feature contribute to Storm Logger's enterprise goals?
**User Impact:** Who will use this feature and how?
**Risk Assessment:** What are the risks if this feature fails?

### 2. Storm Logger Testing Standards
Apply Storm Logger's comprehensive testing approach:
- **90% Coverage Requirement:** Ensure high test coverage
- **Multiple Test Types:** Unit, integration, functional, performance
- **Business Logic Testing:** Verify business intelligence features
- **Professional Quality:** Enterprise-grade reliability

### 3. Test Categories

#### Unit Tests
- **Component Isolation:** Test individual components in isolation
- **Mock Dependencies:** Use mocks for external dependencies
- **Edge Cases:** Test boundary conditions and error scenarios
- **Business Logic:** Verify core business logic implementation

#### Integration Tests
- **Framework Integration:** Test Django, Flask, standalone integration
- **Database Operations:** Verify data persistence and retrieval
- **External Services:** Test integration with external systems
- **Configuration Management:** Test various configuration scenarios

#### Functional Tests
- **End-to-End Scenarios:** Test complete user workflows
- **Business Workflows:** Verify business process implementation
- **Cross-Component:** Test interaction between components
- **Performance Scenarios:** Test under realistic load

#### Performance Tests
- **Throughput:** Test message processing capacity
- **Response Time:** Verify performance requirements
- **Memory Usage:** Test memory efficiency
- **Concurrent Operations:** Test under concurrent load

### 4. Storm Logger Specific Testing

#### Console Testing
- **Rich Output:** Test console formatting and colors
- **Theme Application:** Test different console themes
- **Fallback Behavior:** Test non-TTY environment handling
- **Table Rendering:** Test data table formatting

#### Logger Testing
- **Level Filtering:** Test log level filtering
- **Context Enrichment:** Test context propagation
- **Business Metrics:** Test metrics collection
- **Sanitization:** Test PII and sensitive data handling

#### Configuration Testing
- **Environment Variables:** Test configuration loading
- **Framework Detection:** Test automatic framework detection
- **Validation:** Test configuration validation
- **Defaults:** Test default value handling

### 5. Test Data Strategy
- **Realistic Data:** Use data that mimics production scenarios
- **Edge Case Data:** Test with boundary and error conditions
- **Security Data:** Test with potentially sensitive information
- **Performance Data:** Test with large datasets

### 6. Test Environment Setup
- **Isolated Testing:** Each test should be independent
- **Clean State:** Ensure clean state between tests
- **Resource Management:** Properly manage test resources
- **Parallel Execution:** Support parallel test execution

### 7. Assertion Strategy
- **Specific Assertions:** Test specific behaviors, not just "it works"
- **Error Conditions:** Test error handling and recovery
- **Side Effects:** Test unintended consequences
- **Performance Assertions:** Test performance characteristics

### 8. Test Documentation
- **Test Purpose:** Clear documentation of what each test verifies
- **Test Data:** Document test data and scenarios
- **Setup Requirements:** Document any special setup needs
- **Maintenance Notes:** Document test maintenance requirements

## Test Implementation Plan

Generate a comprehensive test plan that includes:
1. **Test Structure:** How to organize the tests
2. **Test Cases:** Specific test cases to implement
3. **Test Data:** Data needed for testing
4. **Test Execution:** How to run and validate tests
5. **Continuous Integration:** How to integrate with CI/CD
6. **Maintenance:** How to maintain tests over time

Focus on Storm Logger's enterprise requirements and the need for bulletproof reliability.
"""
    return prompt


def generate_mcp_development_workflow(project_name: str, purpose: str) -> str:
    """
    Generate MCP development workflow prompt
    
    Args:
        project_name: Name of the MCP project
        purpose: Purpose of the MCP server
        
    Returns:
        Development workflow prompt text
    """
    prompt = f"""
# MCP Development Workflow: {project_name}

## Project Overview
**Project:** {project_name}
**Purpose:** {purpose}
**Framework:** FastMCP with Storm Logger integration

## Development Methodology

### 1. Storm Logger MCP Standards
Follow Storm Logger's enterprise MCP development standards:
- **Clean Architecture:** Separate concerns and maintainable code
- **Professional Quality:** Enterprise-grade reliability and performance
- **Business Intelligence:** Built-in metrics and monitoring
- **Comprehensive Testing:** 90% coverage requirement

### 2. MCP Component Development

#### Tool Development
- **Clear Interface:** Well-defined parameters and return types
- **Input Validation:** Comprehensive parameter validation
- **Error Handling:** Graceful error handling and reporting
- **Business Logic:** Implement core business functionality
- **Performance:** Optimize for speed and efficiency

#### Resource Development
- **Data Management:** Efficient data loading and caching
- **Version Control:** Handle resource versioning
- **Access Control:** Implement proper access controls
- **Monitoring:** Built-in monitoring and logging

#### Prompt Development
- **Template Design:** Flexible and reusable prompts
- **Context Management:** Proper context handling
- **Validation:** Input and output validation
- **Customization:** Support for customization

### 3. Development Workflow

#### Phase 1: Planning and Design
1. **Requirements Analysis:** Define clear requirements
2. **Architecture Design:** Plan component architecture
3. **Interface Design:** Define clear interfaces
4. **Test Strategy:** Plan comprehensive testing approach

#### Phase 2: Implementation
1. **Core Components:** Implement core functionality
2. **Integration:** Integrate with Storm Logger
3. **Testing:** Implement comprehensive tests
4. **Documentation:** Create thorough documentation

#### Phase 3: Testing and Validation
1. **Unit Testing:** Test individual components
2. **Integration Testing:** Test component interactions
3. **Performance Testing:** Validate performance requirements
4. **User Acceptance:** Validate against requirements

#### Phase 4: Deployment and Monitoring
1. **Deployment:** Deploy to production environment
2. **Monitoring:** Implement comprehensive monitoring
3. **Maintenance:** Ongoing maintenance and updates
4. **Optimization:** Continuous performance optimization

### 4. Quality Assurance

#### Code Quality
- **Linting:** Use Ruff for code linting
- **Formatting:** Use Black for code formatting
- **Type Checking:** Use MyPy for type checking
- **Documentation:** Comprehensive docstrings and comments

#### Testing Quality
- **Coverage:** 90% test coverage requirement
- **Test Types:** Unit, integration, functional tests
- **Test Data:** Realistic and comprehensive test data
- **Automation:** Automated test execution

#### Performance Quality
- **Response Time:** Fast response times
- **Throughput:** High throughput capabilities
- **Resource Usage:** Efficient resource utilization
- **Scalability:** Scalable architecture

### 5. Storm Logger Integration

#### Logging Integration
- **Professional Logging:** Use Storm Logger for all logging
- **Business Metrics:** Track business-relevant metrics
- **Error Tracking:** Comprehensive error tracking
- **Performance Monitoring:** Monitor performance metrics

#### Configuration Integration
- **Environment Variables:** Use Storm Logger configuration patterns
- **Framework Detection:** Automatic framework detection
- **Validation:** Configuration validation
- **Defaults:** Sensible default configurations

### 6. Development Tools

#### Essential Tools
- **FastMCP:** MCP server framework
- **Storm Logger:** Logging and monitoring
- **pytest:** Testing framework
- **Black/Ruff:** Code formatting and linting
- **MyPy:** Type checking

#### Development Environment
- **Virtual Environment:** Isolated development environment
- **Dependencies:** Managed with requirements.txt
- **Version Control:** Git with proper branching
- **CI/CD:** Automated testing and deployment

### 7. Documentation Strategy

#### Code Documentation
- **Docstrings:** Comprehensive function and class documentation
- **Type Hints:** Complete type annotations
- **Comments:** Explain complex logic and decisions
- **Examples:** Provide usage examples

#### User Documentation
- **README:** Clear project overview and setup
- **API Documentation:** Complete API documentation
- **Examples:** Working examples and tutorials
- **Troubleshooting:** Common issues and solutions

## Implementation Roadmap

Create a detailed implementation plan that includes:
1. **Milestone Planning:** Clear milestones and deliverables
2. **Resource Allocation:** Required resources and timeline
3. **Risk Management:** Identified risks and mitigation strategies
4. **Quality Gates:** Quality checkpoints and validation
5. **Success Metrics:** Measurable success criteria

Focus on Storm Logger's enterprise requirements and the $10M revenue goal through superior software quality.
"""
    return prompt


def python_architecture_review(
    project_path: str,
    complexity_level: str = "medium",
    focus_areas: List[str] = None
) -> str:
    """
    Generate Python architecture review prompt
    
    Args:
        project_path: Path to the project to review
        complexity_level: "low", "medium", "high", "enterprise"
        focus_areas: Specific areas to focus on (optional)
        
    Returns:
        Architecture review prompt text
    """
    if focus_areas is None:
        focus_areas = ["structure", "patterns", "performance", "maintainability"]
    
    prompt = f"""
# Python Architecture Review: {project_path}

## Review Parameters
**Project Path:** {project_path}
**Complexity Level:** {complexity_level}
**Focus Areas:** {', '.join(focus_areas)}

## Architecture Review Framework

### 1. Structural Analysis
Analyze the project structure for:
- **Module Organization:** Is the code logically organized into modules?
- **Package Structure:** Are packages well-defined with clear boundaries?
- **Import Patterns:** Are imports clean and circular-import-free?
- **File Organization:** Are files appropriately sized and focused?

### 2. Design Patterns Assessment
Evaluate the use of design patterns:
- **Creational Patterns:** Factory, Builder, Singleton usage
- **Structural Patterns:** Adapter, Decorator, Facade implementation
- **Behavioral Patterns:** Observer, Strategy, Command patterns
- **Python-Specific:** Context managers, descriptors, metaclasses

### 3. Code Quality Metrics
Assess code quality across dimensions:
- **Complexity:** Cyclomatic complexity and cognitive load
- **Coupling:** Inter-module dependencies and coupling strength
- **Cohesion:** Module cohesion and single responsibility
- **Maintainability:** Code readability and modification ease

### 4. Storm Logger Integration Assessment
For Storm Logger compliance:
- **Logging Standards:** Proper logging implementation
- **Business Intelligence:** Metrics collection and reporting
- **Error Handling:** Comprehensive error handling patterns
- **Configuration Management:** Professional configuration handling

### 5. Performance Architecture
Evaluate performance characteristics:
- **Algorithmic Efficiency:** Algorithm choice and implementation
- **Data Structures:** Appropriate data structure usage
- **Memory Management:** Memory usage patterns and optimization
- **I/O Operations:** Efficient I/O handling and async usage

### 6. Security Architecture
Assess security considerations:
- **Input Validation:** Comprehensive input validation
- **Data Sanitization:** Proper data sanitization practices
- **Authentication:** Authentication and authorization patterns
- **Sensitive Data:** Secure handling of sensitive information

### 7. Scalability Assessment
Evaluate scalability potential:
- **Horizontal Scaling:** Support for horizontal scaling
- **Vertical Scaling:** Efficient resource utilization
- **Caching Strategy:** Effective caching implementation
- **Database Design:** Database interaction patterns

### 8. Testing Architecture
Review testing implementation:
- **Test Coverage:** Comprehensive test coverage
- **Test Organization:** Clear test structure and organization
- **Test Dependencies:** Proper test isolation and dependencies
- **Test Performance:** Efficient test execution

## Architecture Review Areas

### Focus Area Analysis
{"For each focus area specified, provide detailed analysis:" if focus_areas else "Provide comprehensive analysis across all areas:"}

{"".join([f"**{area.title()}:** Detailed analysis of this architectural aspect" + chr(10) for area in focus_areas])}

### Improvement Recommendations
1. **Immediate Actions:** Critical issues requiring immediate attention
2. **Short-term Improvements:** Enhancements achievable within weeks
3. **Long-term Refactoring:** Major architectural improvements
4. **Best Practices:** Industry best practices to adopt

### Storm Logger Standards Compliance
- **Enterprise Grade:** Meeting enterprise-grade standards
- **Performance Requirements:** Meeting performance benchmarks
- **Business Intelligence:** Leveraging business intelligence features
- **Professional Quality:** Maintaining professional quality standards

## Architecture Review Checklist

### Code Structure
- [ ] Clear module boundaries and responsibilities
- [ ] Proper package organization
- [ ] Clean import structure
- [ ] Appropriate file sizes and focus

### Design Patterns
- [ ] Appropriate pattern usage
- [ ] Python-specific patterns leveraged
- [ ] Over-engineering avoided
- [ ] Patterns properly implemented

### Quality Metrics
- [ ] Acceptable complexity levels
- [ ] Low coupling between modules
- [ ] High cohesion within modules
- [ ] Good maintainability scores

### Performance
- [ ] Efficient algorithms
- [ ] Appropriate data structures
- [ ] Optimized I/O operations
- [ ] Good memory management

### Security
- [ ] Proper input validation
- [ ] Secure data handling
- [ ] Authentication implemented
- [ ] Sensitive data protected

Provide a comprehensive architecture review that helps achieve Storm Logger's enterprise-grade quality standards.
"""
    return prompt


def python_debugging_strategy(
    error_description: str,
    code_context: str,
    debugging_level: str = "comprehensive"
) -> str:
    """
    Generate Python debugging strategy prompt
    
    Args:
        error_description: Description of the error or issue
        code_context: Context about the code where the error occurs
        debugging_level: "basic", "intermediate", "advanced", "comprehensive"
        
    Returns:
        Debugging strategy prompt text
    """
    prompt = f"""
# Python Debugging Strategy

## Problem Analysis
**Error Description:** {error_description}
**Code Context:** {code_context}
**Debugging Level:** {debugging_level}

## Systematic Debugging Framework

### 1. Error Classification
Classify the error type:
- **Syntax Errors:** Code syntax issues
- **Runtime Errors:** Exceptions during execution
- **Logic Errors:** Incorrect program behavior
- **Performance Issues:** Slow or inefficient execution
- **Integration Errors:** Issues with external systems

### 2. Information Gathering
Collect comprehensive information:
- **Error Messages:** Full error tracebacks and messages
- **Environment Details:** Python version, dependencies, OS
- **Reproduction Steps:** How to consistently reproduce the error
- **Context Information:** Recent changes, environment differences

### 3. Debugging Tools Strategy
Choose appropriate debugging tools:
- **Built-in Debugger:** Python's pdb for interactive debugging
- **IDE Debuggers:** VS Code, PyCharm debugging features
- **Logging:** Strategic logging for error tracking
- **Print Debugging:** Strategic print statements for simple cases
- **Profiling Tools:** For performance-related issues

### 4. Storm Logger Integration
Leverage Storm Logger for debugging:
- **Professional Logging:** Use Storm Logger for comprehensive logging
- **Business Metrics:** Track relevant business metrics
- **Error Tracking:** Comprehensive error tracking and reporting
- **Console Output:** Use Storm Logger's rich console output

### 5. Debugging Methodology

#### Phase 1: Problem Understanding
1. **Reproduce the Error:** Create a minimal reproduction case
2. **Analyze Error Messages:** Parse error messages for clues
3. **Identify Error Location:** Pinpoint where the error occurs
4. **Understand Expected Behavior:** Define what should happen

#### Phase 2: Hypothesis Formation
1. **Generate Hypotheses:** List possible causes
2. **Prioritize Hypotheses:** Rank by likelihood and impact
3. **Design Tests:** Create tests to validate hypotheses
4. **Plan Investigation:** Systematic investigation approach

#### Phase 3: Investigation
1. **Trace Execution:** Follow code execution path
2. **Examine State:** Inspect variables and program state
3. **Test Hypotheses:** Validate or refute hypotheses
4. **Gather Evidence:** Collect supporting or contradicting evidence

#### Phase 4: Solution Implementation
1. **Develop Fix:** Create and test solution
2. **Validate Fix:** Ensure fix addresses root cause
3. **Test Side Effects:** Check for unintended consequences
4. **Document Solution:** Record solution for future reference

### 6. Advanced Debugging Techniques

#### Memory Debugging
- **Memory Profiling:** Use memory profilers to identify leaks
- **Object Tracking:** Track object creation and destruction
- **Garbage Collection:** Understand garbage collection behavior
- **Memory Optimization:** Optimize memory usage patterns

#### Concurrency Debugging
- **Thread Safety:** Identify thread safety issues
- **Race Conditions:** Detect and resolve race conditions
- **Deadlock Detection:** Identify and resolve deadlocks
- **Async Debugging:** Debug asynchronous code execution

#### Performance Debugging
- **Profiling:** Use profilers to identify bottlenecks
- **Timing Analysis:** Measure execution times
- **Resource Usage:** Monitor CPU, memory, I/O usage
- **Optimization:** Implement performance optimizations

### 7. Debugging Best Practices

#### Systematic Approach
- **Document Everything:** Keep detailed debugging notes
- **Version Control:** Use git bisect for regression analysis
- **Test Driven:** Write tests to capture and prevent errors
- **Incremental Changes:** Make small, testable changes

#### Tool Usage
- **Right Tool for the Job:** Choose appropriate debugging tools
- **Automation:** Automate repetitive debugging tasks
- **Monitoring:** Implement monitoring for early detection
- **Logging Strategy:** Strategic logging for troubleshooting

#### Knowledge Management
- **Solution Documentation:** Document solutions for future use
- **Pattern Recognition:** Identify and document common patterns
- **Team Sharing:** Share debugging knowledge with the team
- **Continuous Learning:** Stay updated with debugging techniques

### 8. Storm Logger Debugging Features

#### Professional Logging
- **Structured Logging:** Use structured logging for better analysis
- **Context Propagation:** Maintain context across operations
- **Business Metrics:** Track business-relevant debugging metrics
- **Error Categorization:** Categorize errors for better analysis

#### Console Integration
- **Rich Output:** Use Storm Logger's rich console features
- **Color Coding:** Leverage color coding for better visibility
- **Progress Tracking:** Track debugging progress visually
- **Interactive Features:** Use interactive debugging features

## Debugging Action Plan

### Immediate Actions (Today)
1. **Gather Information:** Collect all relevant error information
2. **Reproduce Error:** Create reliable reproduction steps
3. **Initial Analysis:** Perform initial error analysis
4. **Tool Setup:** Set up appropriate debugging tools

### Short-term Actions (This Week)
1. **Systematic Investigation:** Follow systematic debugging approach
2. **Hypothesis Testing:** Test and validate hypotheses
3. **Solution Development:** Develop and test solutions
4. **Documentation:** Document findings and solutions

### Long-term Actions (Ongoing)
1. **Prevention:** Implement measures to prevent similar errors
2. **Monitoring:** Set up monitoring for early detection
3. **Process Improvement:** Improve debugging processes
4. **Knowledge Sharing:** Share debugging knowledge with team

## Success Metrics
- **Resolution Time:** Time to resolve the issue
- **Solution Quality:** Quality and robustness of the solution
- **Prevention:** Prevention of similar issues in the future
- **Knowledge Transfer:** Successful knowledge transfer to team

Focus on Storm Logger's enterprise requirements and systematic problem-solving approach.
"""
    return prompt


def python_performance_optimization(
    performance_issue: str,
    current_metrics: str,
    optimization_target: str = "comprehensive"
) -> str:
    """
    Generate Python performance optimization prompt
    
    Args:
        performance_issue: Description of the performance issue
        current_metrics: Current performance metrics
        optimization_target: "speed", "memory", "scalability", "comprehensive"
        
    Returns:
        Performance optimization prompt text
    """
    prompt = f"""
# Python Performance Optimization Strategy

## Performance Analysis
**Performance Issue:** {performance_issue}
**Current Metrics:** {current_metrics}
**Optimization Target:** {optimization_target}

## Performance Optimization Framework

### 1. Performance Measurement
Establish baseline measurements:
- **Execution Time:** Function and operation timing
- **Memory Usage:** Memory consumption patterns
- **CPU Utilization:** CPU usage characteristics
- **I/O Performance:** Disk and network I/O metrics
- **Throughput:** Operations per second
- **Response Time:** Request/response latency

### 2. Performance Profiling
Use systematic profiling approaches:
- **Function Profiling:** cProfile for function-level analysis
- **Line Profiling:** line_profiler for line-by-line analysis
- **Memory Profiling:** memory_profiler for memory analysis
- **Statistical Profiling:** py-spy for production profiling
- **Custom Profiling:** Application-specific profiling

### 3. Storm Logger Performance Integration
Leverage Storm Logger's performance features:
- **Performance Tracking:** Built-in performance measurement
- **Business Metrics:** Track performance-related business metrics
- **Professional Logging:** Comprehensive performance logging
- **Console Monitoring:** Real-time performance monitoring

### 4. Optimization Categories

#### Algorithm Optimization
- **Complexity Analysis:** Analyze time and space complexity
- **Algorithm Selection:** Choose optimal algorithms
- **Data Structure Optimization:** Use appropriate data structures
- **Caching Strategies:** Implement effective caching

#### Code-Level Optimization
- **Function Optimization:** Optimize individual functions
- **Loop Optimization:** Optimize iteration patterns
- **String Operations:** Optimize string manipulation
- **Number Operations:** Optimize numerical computations

#### Memory Optimization
- **Memory Profiling:** Identify memory hotspots
- **Object Management:** Optimize object creation/destruction
- **Garbage Collection:** Optimize garbage collection
- **Memory Leaks:** Identify and fix memory leaks

#### I/O Optimization
- **File Operations:** Optimize file I/O operations
- **Network Operations:** Optimize network communications
- **Database Operations:** Optimize database interactions
- **Caching:** Implement strategic caching

### 5. Python-Specific Optimizations

#### Built-in Functions
- **Use Built-ins:** Leverage optimized built-in functions
- **List Comprehensions:** Use comprehensions over loops
- **Generator Expressions:** Use generators for memory efficiency
- **Iterator Patterns:** Implement efficient iteration

#### Advanced Techniques
- **Async Programming:** Use asyncio for I/O-bound operations
- **Multiprocessing:** Use multiprocessing for CPU-bound tasks
- **Cython Integration:** Use Cython for performance-critical code
- **NumPy Integration:** Use NumPy for numerical computations

#### Memory Management
- **Object Pooling:** Reuse objects to reduce allocation overhead
- **Weak References:** Use weak references to break reference cycles
- **Memory Mapping:** Use memory mapping for large files
- **Lazy Loading:** Load data only when needed

### 6. Performance Testing Strategy

#### Benchmark Development
- **Micro-benchmarks:** Test individual functions
- **Macro-benchmarks:** Test complete workflows
- **Stress Testing:** Test under heavy load
- **Load Testing:** Test with realistic workloads

#### Performance Regression Testing
- **Automated Testing:** Automated performance tests
- **Continuous Monitoring:** Continuous performance monitoring
- **Regression Detection:** Detect performance regressions
- **Performance CI/CD:** Integrate performance testing in CI/CD

### 7. Optimization Implementation

#### Phase 1: Measurement and Analysis
1. **Establish Baseline:** Measure current performance
2. **Identify Bottlenecks:** Find performance bottlenecks
3. **Priority Analysis:** Prioritize optimization opportunities
4. **Resource Planning:** Plan optimization resources

#### Phase 2: Optimization Implementation
1. **Quick Wins:** Implement easy optimizations first
2. **Targeted Optimization:** Focus on identified bottlenecks
3. **Iterative Approach:** Implement optimizations iteratively
4. **Validation:** Validate each optimization

#### Phase 3: Testing and Validation
1. **Performance Testing:** Test optimized code
2. **Functionality Testing:** Ensure functionality is preserved
3. **Regression Testing:** Check for performance regressions
4. **User Acceptance:** Validate with real users

#### Phase 4: Monitoring and Maintenance
1. **Performance Monitoring:** Continuous performance monitoring
2. **Maintenance:** Ongoing optimization maintenance
3. **Evolution:** Evolve optimizations over time
4. **Documentation:** Document optimization strategies

### 8. Storm Logger Performance Features

#### Built-in Performance Tracking
- **Execution Time Tracking:** Track function execution times
- **Performance Decorators:** Use performance measurement decorators
- **Business Metrics:** Track performance-related business metrics
- **Professional Reporting:** Generate performance reports

#### Console Performance Monitoring
- **Real-time Monitoring:** Monitor performance in real-time
- **Visual Indicators:** Use visual performance indicators
- **Progress Tracking:** Track optimization progress
- **Interactive Analysis:** Interactive performance analysis

### 9. Optimization Patterns

#### Common Optimization Patterns
- **Memoization:** Cache expensive computations
- **Lazy Evaluation:** Defer computations until needed
- **Batching:** Process items in batches
- **Parallel Processing:** Use parallel processing for independent tasks

#### Anti-patterns to Avoid
- **Premature Optimization:** Don't optimize without measuring
- **Micro-optimizations:** Focus on significant improvements
- **Complexity vs Performance:** Balance complexity and performance
- **Maintenance Overhead:** Consider long-term maintenance costs

### 10. Performance Optimization Checklist

#### Measurement
- [ ] Baseline performance established
- [ ] Bottlenecks identified
- [ ] Profiling tools set up
- [ ] Metrics collection implemented

#### Optimization
- [ ] Algorithm efficiency reviewed
- [ ] Data structures optimized
- [ ] Memory usage optimized
- [ ] I/O operations optimized

#### Testing
- [ ] Performance tests implemented
- [ ] Regression testing in place
- [ ] Load testing completed
- [ ] User acceptance validated

#### Monitoring
- [ ] Performance monitoring active
- [ ] Alerting configured
- [ ] Reporting implemented
- [ ] Maintenance plan established

## Performance Optimization Plan

### Immediate Actions (Today)
1. **Measure Current Performance:** Establish baseline metrics
2. **Identify Critical Bottlenecks:** Find the most impactful issues
3. **Plan Optimization Strategy:** Develop systematic approach
4. **Set Performance Targets:** Define specific performance goals

### Short-term Actions (This Week)
1. **Implement Quick Wins:** Easy optimizations with high impact
2. **Targeted Optimization:** Focus on identified bottlenecks
3. **Performance Testing:** Validate optimization effectiveness
4. **Documentation:** Document optimization strategies

### Long-term Actions (Ongoing)
1. **Continuous Monitoring:** Maintain performance monitoring
2. **Optimization Evolution:** Evolve optimization strategies
3. **Performance Culture:** Build performance-aware culture
4. **Knowledge Sharing:** Share optimization knowledge with team

## Success Metrics
- **Performance Improvement:** Measurable performance gains
- **Resource Efficiency:** Improved resource utilization
- **Scalability:** Enhanced system scalability
- **Maintainability:** Maintained code maintainability

Focus on Storm Logger's enterprise performance requirements and systematic optimization approach.
"""
    return prompt