"""
Python patterns library for Storm Logger development
"""

import json
from typing import Dict, Any, List


def get_python_patterns_library() -> str:
    """
    Get comprehensive Python patterns library
    
    Returns:
        JSON string with design patterns, code patterns, and implementation examples
    """
    patterns = {
        "design_patterns": {
            "creational": {
                "singleton": {
                    "description": "Ensure a class has only one instance",
                    "use_cases": ["Configuration managers", "Logger instances", "Database connections"],
                    "storm_logger_example": """
class StormLogger:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        if not hasattr(self, 'initialized'):
            self.initialized = True
            self.console = StormConsole()
            self.metrics = BusinessMetricsCollector()
""",
                    "thread_safe_example": """
import threading

class ThreadSafeSingleton:
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
        return cls._instance
"""
                },
                "factory": {
                    "description": "Create objects without specifying exact classes",
                    "use_cases": ["Logger creation", "Handler creation", "Integration setup"],
                    "storm_logger_example": """
class LoggerFactory:
    @staticmethod
    def create_logger(framework: str = None) -> StormLogger:
        if framework == 'django':
            return DjangoStormLogger()
        elif framework == 'flask':
            return FlaskStormLogger()
        else:
            return StandaloneStormLogger()
    
    @staticmethod
    def create_handler(handler_type: str):
        handlers = {
            'console': ConsoleHandler,
            'file': FileHandler,
            'database': DatabaseHandler
        }
        return handlers.get(handler_type, ConsoleHandler)()
"""
                },
                "builder": {
                    "description": "Construct complex objects step by step",
                    "use_cases": ["Configuration building", "Query building", "Complex object creation"],
                    "storm_logger_example": """
class ConfigurationBuilder:
    def __init__(self):
        self.config = StormLoggerConfig()
    
    def with_level(self, level: str):
        self.config.level = level
        return self
    
    def with_handler(self, handler):
        self.config.handlers.append(handler)
        return self
    
    def with_formatter(self, formatter):
        self.config.formatter = formatter
        return self
    
    def build(self) -> StormLoggerConfig:
        return self.config

# Usage
config = (ConfigurationBuilder()
          .with_level('INFO')
          .with_handler(ConsoleHandler())
          .with_formatter(JSONFormatter())
          .build())
"""
                }
            },
            "structural": {
                "adapter": {
                    "description": "Allow incompatible interfaces to work together",
                    "use_cases": ["Framework integration", "Legacy system integration", "Third-party APIs"],
                    "storm_logger_example": """
class DjangoAdapter:
    def __init__(self, storm_logger: StormLogger):
        self.storm_logger = storm_logger
    
    def debug(self, message: str, *args, **kwargs):
        self.storm_logger.debug(message, *args, **kwargs)
    
    def info(self, message: str, *args, **kwargs):
        self.storm_logger.info(message, *args, **kwargs)
    
    def warning(self, message: str, *args, **kwargs):
        self.storm_logger.warning(message, *args, **kwargs)
    
    def error(self, message: str, *args, **kwargs):
        self.storm_logger.error(message, *args, **kwargs)
    
    def critical(self, message: str, *args, **kwargs):
        self.storm_logger.critical(message, *args, **kwargs)
"""
                },
                "decorator": {
                    "description": "Add behavior to objects dynamically",
                    "use_cases": ["Performance monitoring", "Caching", "Authentication", "Logging"],
                    "storm_logger_example": """
import functools
import time

def performance_monitor(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        
        logger = StormLogger()
        logger.track_business_event('function_execution', {
            'function': func.__name__,
            'duration': end_time - start_time,
            'args_count': len(args),
            'kwargs_count': len(kwargs)
        })
        
        return result
    return wrapper

@performance_monitor
def business_operation():
    # Your business logic here
    pass
"""
                },
                "facade": {
                    "description": "Provide a simplified interface to complex subsystems",
                    "use_cases": ["API simplification", "Complex system integration", "Legacy system wrapping"],
                    "storm_logger_example": """
class StormLoggerFacade:
    def __init__(self):
        self.logger = StormLogger()
        self.console = StormConsole()
        self.metrics = BusinessMetricsCollector()
    
    def log_business_success(self, message: str, data: Dict[str, Any] = None):
        self.logger.info(message, extra=data)
        self.console.print_success(message)
        self.metrics.track_success_event(message, data)
    
    def log_business_error(self, message: str, error: Exception = None):
        self.logger.error(message, exc_info=error)
        self.console.print_error(message)
        self.metrics.track_error_event(message, error)
"""
                }
            },
            "behavioral": {
                "observer": {
                    "description": "Define a one-to-many dependency between objects",
                    "use_cases": ["Event handling", "Model-View patterns", "Plugin systems"],
                    "storm_logger_example": """
class EventDispatcher:
    def __init__(self):
        self.observers = []
    
    def add_observer(self, observer):
        self.observers.append(observer)
    
    def remove_observer(self, observer):
        self.observers.remove(observer)
    
    def notify(self, event_type: str, data: Any):
        for observer in self.observers:
            observer.handle_event(event_type, data)

class LoggingObserver:
    def __init__(self, logger: StormLogger):
        self.logger = logger
    
    def handle_event(self, event_type: str, data: Any):
        self.logger.info(f"Event occurred: {event_type}", extra={'data': data})

class MetricsObserver:
    def __init__(self, metrics: BusinessMetricsCollector):
        self.metrics = metrics
    
    def handle_event(self, event_type: str, data: Any):
        self.metrics.track_business_event(event_type, data)
"""
                },
                "strategy": {
                    "description": "Define a family of algorithms and make them interchangeable",
                    "use_cases": ["Algorithm selection", "Configuration strategies", "Processing strategies"],
                    "storm_logger_example": """
class FormattingStrategy:
    def format(self, message: str, data: Dict[str, Any]) -> str:
        raise NotImplementedError

class JSONFormattingStrategy(FormattingStrategy):
    def format(self, message: str, data: Dict[str, Any]) -> str:
        return json.dumps({'message': message, 'data': data})

class TextFormattingStrategy(FormattingStrategy):
    def format(self, message: str, data: Dict[str, Any]) -> str:
        return f"{message} - {data}"

class StormLoggerWithStrategy:
    def __init__(self, strategy: FormattingStrategy):
        self.strategy = strategy
    
    def log(self, message: str, data: Dict[str, Any] = None):
        formatted = self.strategy.format(message, data or {})
        print(formatted)
"""
                },
                "command": {
                    "description": "Encapsulate a request as an object",
                    "use_cases": ["Operation queuing", "Undo/redo operations", "Macro commands"],
                    "storm_logger_example": """
class LogCommand:
    def __init__(self, logger: StormLogger, level: str, message: str, data: Dict[str, Any] = None):
        self.logger = logger
        self.level = level
        self.message = message
        self.data = data or {}
    
    def execute(self):
        getattr(self.logger, self.level.lower())(self.message, extra=self.data)

class CommandQueue:
    def __init__(self):
        self.commands = []
    
    def add_command(self, command: LogCommand):
        self.commands.append(command)
    
    def execute_all(self):
        for command in self.commands:
            command.execute()
        self.commands.clear()
"""
                }
            }
        },
        "python_specific_patterns": {
            "context_manager": {
                "description": "Manage resources and ensure cleanup",
                "use_cases": ["Resource management", "Temporary state", "Exception handling"],
                "storm_logger_example": """
class StormLoggerContext:
    def __init__(self, logger: StormLogger, context_data: Dict[str, Any]):
        self.logger = logger
        self.context_data = context_data
        self.original_context = None
    
    def __enter__(self):
        self.original_context = self.logger.get_context()
        self.logger.update_context(self.context_data)
        return self.logger
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.logger.set_context(self.original_context)
        if exc_type:
            self.logger.error(f"Exception in context: {exc_val}")

# Usage
with StormLoggerContext(logger, {'operation': 'data_processing'}):
    logger.info("Processing data")
"""
            },
            "descriptor": {
                "description": "Customize attribute access",
                "use_cases": ["Property validation", "Computed properties", "Attribute logging"],
                "storm_logger_example": """
class LoggedAttribute:
    def __init__(self, name: str):
        self.name = name
        self.private_name = f'_{name}'
    
    def __get__(self, obj, objtype=None):
        if obj is None:
            return self
        return getattr(obj, self.private_name)
    
    def __set__(self, obj, value):
        old_value = getattr(obj, self.private_name, None)
        setattr(obj, self.private_name, value)
        
        if hasattr(obj, 'logger'):
            obj.logger.debug(f"Attribute {self.name} changed from {old_value} to {value}")

class ConfigurationClass:
    level = LoggedAttribute('level')
    
    def __init__(self):
        self.logger = StormLogger()
        self.level = 'INFO'
"""
            },
            "metaclass": {
                "description": "Control class creation",
                "use_cases": ["ORM implementations", "Singletons", "Class registration"],
                "storm_logger_example": """
class StormLoggerMeta(type):
    def __new__(cls, name, bases, namespace):
        # Add logging to all methods
        for key, value in namespace.items():
            if callable(value) and not key.startswith('_'):
                namespace[key] = cls.add_logging(value)
        
        return super().__new__(cls, name, bases, namespace)
    
    @staticmethod
    def add_logging(func):
        @functools.wraps(func)
        def wrapper(self, *args, **kwargs):
            logger = getattr(self, 'logger', None)
            if logger:
                logger.debug(f"Calling {func.__name__}")
            return func(self, *args, **kwargs)
        return wrapper

class BusinessLogic(metaclass=StormLoggerMeta):
    def __init__(self):
        self.logger = StormLogger()
    
    def process_data(self, data):
        # This method will automatically have logging
        pass
"""
            },
            "property": {
                "description": "Create managed attributes",
                "use_cases": ["Computed properties", "Validation", "Lazy loading"],
                "storm_logger_example": """
class StormLoggerConfig:
    def __init__(self):
        self._level = 'INFO'
        self.logger = StormLogger()
    
    @property
    def level(self):
        return self._level
    
    @level.setter
    def level(self, value):
        valid_levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']
        if value not in valid_levels:
            raise ValueError(f"Invalid level: {value}")
        
        old_level = self._level
        self._level = value
        self.logger.info(f"Log level changed from {old_level} to {value}")
    
    @property
    def is_debug_enabled(self):
        return self._level == 'DEBUG'
"""
            }
        },
        "functional_patterns": {
            "higher_order_functions": {
                "description": "Functions that take or return other functions",
                "use_cases": ["Decorators", "Callbacks", "Function composition"],
                "storm_logger_example": """
def create_logger_decorator(level: str):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            logger = StormLogger()
            getattr(logger, level.lower())(f"Executing {func.__name__}")
            return func(*args, **kwargs)
        return wrapper
    return decorator

@create_logger_decorator('INFO')
def business_operation():
    pass
"""
            },
            "closure": {
                "description": "Functions that capture variables from their enclosing scope",
                "use_cases": ["Configuration capture", "State preservation", "Callback creation"],
                "storm_logger_example": """
def create_logger_with_context(context_data: Dict[str, Any]):
    logger = StormLogger()
    
    def log_with_context(level: str, message: str, **kwargs):
        combined_data = {**context_data, **kwargs}
        getattr(logger, level.lower())(message, extra=combined_data)
    
    return log_with_context

# Usage
user_logger = create_logger_with_context({'user_id': 123, 'session_id': 'abc123'})
user_logger('info', 'User action performed', action='login')
"""
            },
            "generator": {
                "description": "Functions that yield values instead of returning them",
                "use_cases": ["Memory-efficient iteration", "Lazy evaluation", "Stream processing"],
                "storm_logger_example": """
def log_stream_processor(data_stream, logger: StormLogger):
    for item in data_stream:
        logger.debug(f"Processing item: {item}")
        processed = process_item(item)
        logger.debug(f"Processed result: {processed}")
        yield processed

def process_large_dataset(dataset):
    logger = StormLogger()
    processor = log_stream_processor(dataset, logger)
    
    for result in processor:
        # Process results one at a time without loading everything into memory
        handle_result(result)
"""
            }
        },
        "concurrency_patterns": {
            "thread_pool": {
                "description": "Manage a pool of worker threads",
                "use_cases": ["Parallel processing", "I/O-bound tasks", "Background tasks"],
                "storm_logger_example": """
import concurrent.futures
import threading

class ThreadSafeLogger:
    def __init__(self):
        self.logger = StormLogger()
        self.lock = threading.Lock()
    
    def log(self, level: str, message: str, **kwargs):
        with self.lock:
            getattr(self.logger, level.lower())(message, **kwargs)

def process_with_threads(data_items):
    thread_safe_logger = ThreadSafeLogger()
    
    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
        futures = []
        for item in data_items:
            future = executor.submit(process_item_with_logging, item, thread_safe_logger)
            futures.append(future)
        
        for future in concurrent.futures.as_completed(futures):
            result = future.result()
            thread_safe_logger.log('info', f"Completed processing: {result}")
"""
            },
            "async_context_manager": {
                "description": "Asynchronous context managers",
                "use_cases": ["Async resource management", "Database connections", "HTTP sessions"],
                "storm_logger_example": """
import asyncio

class AsyncStormLoggerContext:
    def __init__(self, logger: StormLogger, context_data: Dict[str, Any]):
        self.logger = logger
        self.context_data = context_data
        self.original_context = None
    
    async def __aenter__(self):
        self.original_context = self.logger.get_context()
        self.logger.update_context(self.context_data)
        self.logger.info("Entering async context")
        return self.logger
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        self.logger.set_context(self.original_context)
        if exc_type:
            self.logger.error(f"Exception in async context: {exc_val}")
        self.logger.info("Exiting async context")

# Usage
async def async_operation():
    logger = StormLogger()
    async with AsyncStormLoggerContext(logger, {'operation': 'async_processing'}):
        await asyncio.sleep(1)
        logger.info("Async operation completed")
"""
            },
            "producer_consumer": {
                "description": "Separate data production from consumption",
                "use_cases": ["Queue processing", "Event handling", "Data pipelines"],
                "storm_logger_example": """
import asyncio
from asyncio import Queue

class LoggedQueue:
    def __init__(self, maxsize: int = 0):
        self.queue = Queue(maxsize=maxsize)
        self.logger = StormLogger()
    
    async def put(self, item):
        await self.queue.put(item)
        self.logger.debug(f"Added item to queue: {item}")
    
    async def get(self):
        item = await self.queue.get()
        self.logger.debug(f"Retrieved item from queue: {item}")
        return item

async def producer(queue: LoggedQueue):
    for i in range(10):
        await queue.put(f"item_{i}")
        await asyncio.sleep(0.1)

async def consumer(queue: LoggedQueue):
    while True:
        item = await queue.get()
        # Process item
        await asyncio.sleep(0.2)
        queue.queue.task_done()
"""
            }
        },
        "error_handling_patterns": {
            "exception_chaining": {
                "description": "Chain exceptions to preserve context",
                "use_cases": ["Error context preservation", "Debugging", "Error reporting"],
                "storm_logger_example": """
class StormLoggerError(Exception):
    pass

def process_data_with_context(data):
    logger = StormLogger()
    
    try:
        # Some operation that might fail
        result = risky_operation(data)
        return result
    except ValueError as e:
        logger.error(f"Data processing failed: {e}")
        raise StormLoggerError(f"Failed to process data: {data}") from e
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        raise StormLoggerError("Unexpected error during data processing") from e
"""
            },
            "retry_pattern": {
                "description": "Automatically retry failed operations",
                "use_cases": ["Network requests", "Database operations", "External API calls"],
                "storm_logger_example": """
import time
import random

def retry_with_logging(max_retries: int = 3, delay: float = 1.0):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            logger = StormLogger()
            
            for attempt in range(max_retries):
                try:
                    result = func(*args, **kwargs)
                    if attempt > 0:
                        logger.info(f"Operation succeeded after {attempt + 1} attempts")
                    return result
                except Exception as e:
                    logger.warning(f"Attempt {attempt + 1} failed: {e}")
                    if attempt == max_retries - 1:
                        logger.error(f"All {max_retries} attempts failed")
                        raise
                    time.sleep(delay * (2 ** attempt))  # Exponential backoff
            
        return wrapper
    return decorator

@retry_with_logging(max_retries=3, delay=0.5)
def unreliable_operation():
    if random.random() < 0.7:
        raise Exception("Random failure")
    return "Success"
"""
            }
        }
    }
    
    return json.dumps(patterns, indent=2)


def get_python_architecture_patterns() -> str:
    """
    Get Python architecture patterns for large applications
    
    Returns:
        JSON string with architecture patterns and best practices
    """
    patterns = {
        "layered_architecture": {
            "description": "Organize code into layers with clear responsibilities",
            "layers": {
                "presentation": {
                    "responsibility": "User interface and API endpoints",
                    "components": ["Controllers", "Views", "Serializers", "Validators"]
                },
                "business": {
                    "responsibility": "Business logic and rules",
                    "components": ["Services", "Domain Models", "Business Rules"]
                },
                "data": {
                    "responsibility": "Data access and persistence",
                    "components": ["Repositories", "Data Access Objects", "Database Models"]
                }
            },
            "storm_logger_example": """
# Presentation Layer
class UserController:
    def __init__(self, user_service: UserService):
        self.user_service = user_service
        self.logger = StormLogger()
    
    def create_user(self, user_data: dict):
        self.logger.info("Creating user", extra=user_data)
        try:
            user = self.user_service.create_user(user_data)
            self.logger.track_business_event('user_created', {'user_id': user.id})
            return user
        except Exception as e:
            self.logger.error(f"User creation failed: {e}")
            raise

# Business Layer
class UserService:
    def __init__(self, user_repository: UserRepository):
        self.user_repository = user_repository
        self.logger = StormLogger()
    
    def create_user(self, user_data: dict):
        self.logger.debug("Validating user data")
        self.validate_user_data(user_data)
        return self.user_repository.create(user_data)

# Data Layer
class UserRepository:
    def __init__(self, db_connection):
        self.db = db_connection
        self.logger = StormLogger()
    
    def create(self, user_data: dict):
        self.logger.debug("Saving user to database")
        # Database operation
        return saved_user
"""
        },
        "dependency_injection": {
            "description": "Inject dependencies rather than creating them",
            "benefits": ["Testability", "Flexibility", "Decoupling"],
            "storm_logger_example": """
from typing import Protocol

class LoggerProtocol(Protocol):
    def info(self, message: str, **kwargs): ...
    def error(self, message: str, **kwargs): ...

class UserService:
    def __init__(self, logger: LoggerProtocol, user_repository: UserRepository):
        self.logger = logger
        self.user_repository = user_repository
    
    def create_user(self, user_data: dict):
        self.logger.info("Creating user")
        return self.user_repository.create(user_data)

# Dependency injection container
class DIContainer:
    def __init__(self):
        self._services = {}
    
    def register(self, interface, implementation):
        self._services[interface] = implementation
    
    def get(self, interface):
        return self._services[interface]

# Setup
container = DIContainer()
container.register(LoggerProtocol, StormLogger())
container.register(UserRepository, UserRepository(db_connection))

user_service = UserService(
    container.get(LoggerProtocol),
    container.get(UserRepository)
)
"""
        },
        "event_driven_architecture": {
            "description": "Use events to communicate between components",
            "components": ["Event Bus", "Event Handlers", "Event Publishers"],
            "storm_logger_example": """
from typing import Callable, Dict, List

class EventBus:
    def __init__(self):
        self.handlers: Dict[str, List[Callable]] = {}
        self.logger = StormLogger()
    
    def subscribe(self, event_type: str, handler: Callable):
        if event_type not in self.handlers:
            self.handlers[event_type] = []
        self.handlers[event_type].append(handler)
        self.logger.debug(f"Subscribed handler to {event_type}")
    
    def publish(self, event_type: str, data: Any):
        self.logger.info(f"Publishing event: {event_type}", extra={'data': data})
        for handler in self.handlers.get(event_type, []):
            try:
                handler(data)
            except Exception as e:
                self.logger.error(f"Event handler failed: {e}")

# Event handlers
def log_user_created(user_data):
    logger = StormLogger()
    logger.track_business_event('user_created', user_data)

def send_welcome_email(user_data):
    logger = StormLogger()
    logger.info("Sending welcome email", extra=user_data)

# Setup
event_bus = EventBus()
event_bus.subscribe('user_created', log_user_created)
event_bus.subscribe('user_created', send_welcome_email)

# Usage
event_bus.publish('user_created', {'user_id': 123, 'email': 'user@example.com'})
"""
        },
        "repository_pattern": {
            "description": "Abstract data access logic",
            "benefits": ["Testability", "Data source independence", "Centralized queries"],
            "storm_logger_example": """
from abc import ABC, abstractmethod

class UserRepository(ABC):
    @abstractmethod
    def create(self, user_data: dict): ...
    
    @abstractmethod
    def find_by_id(self, user_id: int): ...

class DatabaseUserRepository(UserRepository):
    def __init__(self, db_connection):
        self.db = db_connection
        self.logger = StormLogger()
    
    def create(self, user_data: dict):
        self.logger.debug("Creating user in database")
        # Database-specific implementation
        return created_user
    
    def find_by_id(self, user_id: int):
        self.logger.debug(f"Finding user by ID: {user_id}")
        # Database-specific implementation
        return found_user

class InMemoryUserRepository(UserRepository):
    def __init__(self):
        self.users = {}
        self.logger = StormLogger()
    
    def create(self, user_data: dict):
        self.logger.debug("Creating user in memory")
        # In-memory implementation
        return created_user
    
    def find_by_id(self, user_id: int):
        self.logger.debug(f"Finding user by ID: {user_id}")
        return self.users.get(user_id)
"""
        },
        "cqrs_pattern": {
            "description": "Separate read and write operations",
            "benefits": ["Scalability", "Performance optimization", "Complex domain modeling"],
            "storm_logger_example": """
# Command side (writes)
class CreateUserCommand:
    def __init__(self, user_data: dict):
        self.user_data = user_data

class UserCommandHandler:
    def __init__(self, user_repository: UserRepository):
        self.user_repository = user_repository
        self.logger = StormLogger()
    
    def handle(self, command: CreateUserCommand):
        self.logger.info("Handling create user command")
        user = self.user_repository.create(command.user_data)
        self.logger.track_business_event('user_created', {'user_id': user.id})
        return user

# Query side (reads)
class UserQuery:
    def __init__(self, user_id: int):
        self.user_id = user_id

class UserQueryHandler:
    def __init__(self, user_read_repository: UserReadRepository):
        self.user_read_repository = user_read_repository
        self.logger = StormLogger()
    
    def handle(self, query: UserQuery):
        self.logger.debug(f"Handling user query: {query.user_id}")
        return self.user_read_repository.find_by_id(query.user_id)
"""
        }
    }
    
    return json.dumps(patterns, indent=2)


def get_python_testing_patterns() -> str:
    """
    Get Python testing patterns and best practices
    
    Returns:
        JSON string with testing patterns and examples
    """
    patterns = {
        "test_patterns": {
            "arrange_act_assert": {
                "description": "Structure tests with clear setup, execution, and verification",
                "storm_logger_example": """
def test_user_creation():
    # Arrange
    logger = StormLogger()
    user_service = UserService(logger, user_repository)
    user_data = {'name': 'John Doe', 'email': 'john@example.com'}
    
    # Act
    user = user_service.create_user(user_data)
    
    # Assert
    assert user.name == 'John Doe'
    assert user.email == 'john@example.com'
    # Verify logging occurred
    assert logger.log_entries[-1]['message'] == 'User created successfully'
"""
            },
            "test_fixtures": {
                "description": "Set up test data and environment",
                "storm_logger_example": """
import pytest

@pytest.fixture
def storm_logger():
    logger = StormLogger()
    logger.set_level('DEBUG')
    return logger

@pytest.fixture
def user_data():
    return {
        'name': 'Test User',
        'email': 'test@example.com',
        'age': 30
    }

@pytest.fixture
def user_service(storm_logger):
    repository = InMemoryUserRepository()
    return UserService(storm_logger, repository)

def test_user_creation(user_service, user_data):
    user = user_service.create_user(user_data)
    assert user.name == user_data['name']
"""
            },
            "mocking": {
                "description": "Replace dependencies with test doubles",
                "storm_logger_example": """
from unittest.mock import Mock, patch

def test_user_creation_with_mock():
    # Mock the repository
    mock_repository = Mock()
    mock_repository.create.return_value = User(id=1, name='Test User')
    
    # Mock the logger
    mock_logger = Mock()
    
    # Create service with mocks
    user_service = UserService(mock_logger, mock_repository)
    
    # Execute
    user = user_service.create_user({'name': 'Test User'})
    
    # Verify
    assert user.id == 1
    mock_repository.create.assert_called_once()
    mock_logger.info.assert_called_once()

@patch('storm_logger.StormLogger')
def test_with_patch(mock_logger_class):
    mock_logger = Mock()
    mock_logger_class.return_value = mock_logger
    
    service = UserService(mock_logger, repository)
    service.create_user({'name': 'Test'})
    
    mock_logger.info.assert_called()
"""
            },
            "parametrized_tests": {
                "description": "Run the same test with different inputs",
                "storm_logger_example": """
import pytest

@pytest.mark.parametrize("user_data,expected_error", [
    ({'name': '', 'email': 'test@example.com'}, 'Name is required'),
    ({'name': 'Test', 'email': ''}, 'Email is required'),
    ({'name': 'Test', 'email': 'invalid'}, 'Invalid email format'),
])
def test_user_validation(user_service, user_data, expected_error):
    with pytest.raises(ValidationError) as exc_info:
        user_service.create_user(user_data)
    
    assert str(exc_info.value) == expected_error
"""
            },
            "integration_tests": {
                "description": "Test component interactions",
                "storm_logger_example": """
@pytest.mark.integration
def test_user_creation_end_to_end():
    # Setup real dependencies
    logger = StormLogger()
    db_connection = create_test_database()
    repository = DatabaseUserRepository(db_connection)
    service = UserService(logger, repository)
    
    # Execute
    user_data = {'name': 'Integration Test', 'email': 'integration@test.com'}
    user = service.create_user(user_data)
    
    # Verify in database
    saved_user = repository.find_by_id(user.id)
    assert saved_user.name == user_data['name']
    
    # Verify logging
    log_entries = logger.get_log_entries()
    assert any('User created successfully' in entry['message'] for entry in log_entries)
"""
            },
            "property_based_testing": {
                "description": "Test with generated inputs",
                "storm_logger_example": """
from hypothesis import given, strategies as st

@given(st.text(min_size=1, max_size=100))
def test_user_name_handling(name):
    logger = StormLogger()
    service = UserService(logger, repository)
    
    user_data = {'name': name, 'email': 'test@example.com'}
    user = service.create_user(user_data)
    
    assert user.name == name
    assert len(logger.get_log_entries()) > 0

@given(st.emails())
def test_email_validation(email):
    logger = StormLogger()
    service = UserService(logger, repository)
    
    user_data = {'name': 'Test', 'email': email}
    user = service.create_user(user_data)
    
    assert user.email == email
"""
            }
        }
    }
    
    return json.dumps(patterns, indent=2)