"""
Test pattern suggestion logic for Storm Logger
"""

import json
from typing import Dict, Any, List, Optional


def suggest_patterns(feature_name: str, test_type: str = "unit", modified_files: Optional[List[str]] = None) -> str:
    """
    Recommend test patterns and -k filters based on current development context
    
    Args:
        feature_name: Name of feature being worked on (e.g., "console_table_printing")
        test_type: Type of test (unit, integration, functional, performance)
        modified_files: List of recently modified files
        
    Returns:
        JSON string with recommended test patterns and commands
    """
    if modified_files is None:
        modified_files = []
        
    suggestions = {
        "feature_name": feature_name,
        "test_type": test_type,
        "recommended_patterns": [],
        "storm_commands": [],
        "test_strategies": [],
        "naming_conventions": {}
    }
    
    # Generate test patterns based on feature
    feature_clean = feature_name.lower().replace("-", "_").replace(" ", "_")
    
    # Basic patterns
    patterns = [
        f"test_{feature_clean}",
        f"{feature_clean}",
        f"Test{feature_name.replace('_', '').title()}"
    ]
    
    # Component-specific patterns
    if "console" in feature_clean:
        patterns.extend([
            "console and print",
            "StormConsole",
            "console and format"
        ])
    elif "logger" in feature_clean:
        patterns.extend([
            "logger and business",
            "ProfessionalStormLogger", 
            "logger and metric"
        ])
    elif "config" in feature_clean:
        patterns.extend([
            "config and django",
            "StormLoggerConfig",
            "config and validation"
        ])
    
    suggestions["recommended_patterns"] = patterns
    
    # Generate Storm commands for different scenarios
    commands = []
    
    # Development workflow commands
    for pattern in patterns[:3]:  # Use top 3 patterns
        commands.extend([
            f"./test.sh -k \"{pattern}\" --quick",
            f"./test.sh -k \"{pattern}\" -v",
            f"./test.sh -k \"{pattern}\" --quick --progress"
        ])
    
    # Test type specific commands
    if test_type == "unit":
        commands.extend([
            "./test.sh --quick",
            f"./test.sh -k \"unit and {feature_clean}\"" 
        ])
    elif test_type == "integration":
        commands.extend([
            "./test.sh --full",
            f"./test.sh -k \"integration and {feature_clean}\""
        ])
    elif test_type == "performance":
        commands.extend([
            f"./test.sh -k \"performance and {feature_clean}\"",
            f"./test.sh -k \"benchmark and {feature_clean}\""
        ])
    
    # Add debugging commands
    commands.extend([
        "./test.sh --failed",
        f"./test.sh -k \"{feature_clean}\" --all-failures"
    ])
    
    suggestions["storm_commands"] = list(set(commands))  # Remove duplicates
    
    # Test strategies based on feature type
    if "console" in feature_clean:
        suggestions["test_strategies"] = [
            "Mock Rich console components for isolation",
            "Test theme application and color schemes",
            "Verify fallback behavior for non-TTY environments",
            "Test output formatting with various data types"
        ]
    elif "logger" in feature_clean:
        suggestions["test_strategies"] = [
            "Test with different log levels and configurations",
            "Mock file system operations for reliability", 
            "Verify business metrics collection",
            "Test context propagation and enrichment"
        ]
    else:
        suggestions["test_strategies"] = [
            "Test happy path scenarios thoroughly",
            "Cover edge cases and error conditions",
            "Mock external dependencies",
            "Verify integration points"
        ]
    
    # Naming conventions
    suggestions["naming_conventions"] = {
        "test_files": f"test_{feature_clean}.py",
        "test_classes": f"Test{feature_name.replace('_', '').title()}",
        "test_methods": f"test_{feature_clean}_*",
        "fixtures": f"{feature_clean}_fixture",
        "mocks": f"mock_{feature_clean}"
    }
    
    # File-specific suggestions
    if modified_files:
        file_suggestions = []
        for file_path in modified_files:
            if "console" in file_path:
                file_suggestions.append("Focus on console output formatting tests")
            elif "config" in file_path:
                file_suggestions.append("Test configuration validation and loading")
            elif "integration" in file_path:
                file_suggestions.append("Test framework-specific integrations")
                
        suggestions["file_specific_advice"] = file_suggestions
    
    return json.dumps(suggestions, indent=2)


def generate_basic_patterns(feature_name: str) -> List[str]:
    """
    Generate basic test patterns for a feature
    
    Args:
        feature_name: Name of the feature
        
    Returns:
        List of basic test patterns
    """
    feature_clean = feature_name.lower().replace("-", "_").replace(" ", "_")
    
    return [
        f"test_{feature_clean}",
        f"{feature_clean}",
        f"Test{feature_name.replace('_', '').title()}"
    ]


def generate_component_patterns(feature_name: str) -> List[str]:
    """
    Generate component-specific test patterns
    
    Args:
        feature_name: Name of the feature
        
    Returns:
        List of component-specific patterns
    """
    feature_clean = feature_name.lower().replace("-", "_").replace(" ", "_")
    patterns = []
    
    if "console" in feature_clean:
        patterns.extend([
            "console and print",
            "StormConsole",
            "console and format",
            "console and table",
            "console and theme"
        ])
    elif "logger" in feature_clean:
        patterns.extend([
            "logger and business",
            "ProfessionalStormLogger", 
            "logger and metric",
            "logger and context",
            "logger and format"
        ])
    elif "config" in feature_clean:
        patterns.extend([
            "config and django",
            "StormLoggerConfig",
            "config and validation",
            "config and setup",
            "config and environment"
        ])
    elif "integration" in feature_clean:
        patterns.extend([
            "integration and django",
            "integration and flask",
            "integration and standalone",
            "integration and framework"
        ])
    
    return patterns


def generate_storm_commands(feature_name: str, test_type: str) -> List[str]:
    """
    Generate Storm test commands for different scenarios
    
    Args:
        feature_name: Name of the feature
        test_type: Type of test
        
    Returns:
        List of Storm test commands
    """
    feature_clean = feature_name.lower().replace("-", "_").replace(" ", "_")
    patterns = generate_basic_patterns(feature_name)
    commands = []
    
    # Development workflow commands
    for pattern in patterns[:3]:  # Use top 3 patterns
        commands.extend([
            f"./test.sh -k \"{pattern}\" --quick",
            f"./test.sh -k \"{pattern}\" -v",
            f"./test.sh -k \"{pattern}\" --quick --progress"
        ])
    
    # Test type specific commands
    if test_type == "unit":
        commands.extend([
            "./test.sh --quick",
            f"./test.sh -k \"unit and {feature_clean}\"" 
        ])
    elif test_type == "integration":
        commands.extend([
            "./test.sh --full",
            f"./test.sh -k \"integration and {feature_clean}\""
        ])
    elif test_type == "performance":
        commands.extend([
            f"./test.sh -k \"performance and {feature_clean}\"",
            f"./test.sh -k \"benchmark and {feature_clean}\""
        ])
    
    # Add debugging commands
    commands.extend([
        "./test.sh --failed",
        f"./test.sh -k \"{feature_clean}\" --all-failures"
    ])
    
    return list(set(commands))  # Remove duplicates


def get_test_strategies(feature_name: str) -> List[str]:
    """
    Get test strategies based on feature type
    
    Args:
        feature_name: Name of the feature
        
    Returns:
        List of test strategies
    """
    feature_clean = feature_name.lower().replace("-", "_").replace(" ", "_")
    
    if "console" in feature_clean:
        return [
            "Mock Rich console components for isolation",
            "Test theme application and color schemes",
            "Verify fallback behavior for non-TTY environments",
            "Test output formatting with various data types",
            "Test table rendering with different data structures",
            "Verify color and style application"
        ]
    elif "logger" in feature_clean:
        return [
            "Test with different log levels and configurations",
            "Mock file system operations for reliability", 
            "Verify business metrics collection",
            "Test context propagation and enrichment",
            "Test performance under load",
            "Verify sanitization of sensitive data"
        ]
    elif "config" in feature_clean:
        return [
            "Test configuration validation and loading",
            "Test environment variable handling",
            "Test default value fallbacks",
            "Test configuration merging",
            "Test framework-specific configurations"
        ]
    else:
        return [
            "Test happy path scenarios thoroughly",
            "Cover edge cases and error conditions",
            "Mock external dependencies",
            "Verify integration points",
            "Test error handling and recovery",
            "Verify performance characteristics"
        ]


def get_naming_conventions(feature_name: str) -> Dict[str, str]:
    """
    Get naming conventions for test components
    
    Args:
        feature_name: Name of the feature
        
    Returns:
        Dictionary with naming conventions
    """
    feature_clean = feature_name.lower().replace("-", "_").replace(" ", "_")
    
    return {
        "test_files": f"test_{feature_clean}.py",
        "test_classes": f"Test{feature_name.replace('_', '').title()}",
        "test_methods": f"test_{feature_clean}_*",
        "fixtures": f"{feature_clean}_fixture",
        "mocks": f"mock_{feature_clean}",
        "test_data": f"{feature_clean}_test_data",
        "helpers": f"{feature_clean}_helpers"
    }


def get_file_specific_advice(modified_files: List[str]) -> List[str]:
    """
    Get file-specific testing advice
    
    Args:
        modified_files: List of modified files
        
    Returns:
        List of file-specific advice
    """
    advice = []
    
    for file_path in modified_files:
        if "console" in file_path:
            advice.append("Focus on console output formatting tests")
            advice.append("Test Rich component integration")
            advice.append("Verify theme application")
        elif "config" in file_path:
            advice.append("Test configuration validation and loading")
            advice.append("Test environment variable handling")
            advice.append("Test default value fallbacks")
        elif "integration" in file_path:
            advice.append("Test framework-specific integrations")
            advice.append("Test configuration management")
            advice.append("Test middleware and hooks")
        elif "logger" in file_path:
            advice.append("Test logging behavior and output")
            advice.append("Test business metrics collection")
            advice.append("Test context propagation")
        elif "utils" in file_path:
            advice.append("Test utility functions thoroughly")
            advice.append("Test edge cases and error conditions")
            advice.append("Test performance characteristics")
    
    return list(set(advice))  # Remove duplicates