# Hephaestus Code Style & Conventions

## Python Code Standards

### General Style
- **Python Version**: 3.13+ with modern type annotations
- **Formatting**: ruff (configured in pyproject.toml)
- **Linting**: ruff check for code quality
- **Type Checking**: basedpyright with minimal configuration
- **Documentation**: Docstrings for public APIs and functions

### Naming Conventions
- **Classes**: PascalCase (e.g., `HephaestusMCPServer`)
- **Functions/Variables**: snake_case (e.g., `main`, `mcp_server`)
- **Constants**: UPPER_SNAKE_CASE (e.g., `DEFAULT_PORT`)
- **Private**: Leading underscore (e.g., `_internal_method`)

### Type Annotations
- Use modern Python 3.13+ type hints
- Return types always specified (`-> None`, `-> str`)
- Parameter types always specified (`host: str`, `port: int`)
- Use `|` for union types instead of `Union`

### Import Style
- Standard library imports first
- Third-party imports second
- Local imports third
- Use `from module import specific` for clarity
- Avoid wildcard imports (`from module import *`)

### Code Structure
- **Classes**: Group related functionality, clear single responsibility
- **Functions**: Small, focused, single purpose
- **Modules**: Logical grouping of related code
- **Packages**: Clear hierarchy and separation of concerns

## Anvil Code Generation Standards

### YAML Form
- **Indentation**: 2 spaces for YAML structure
- **Component IDs**: snake_case with type prefixes (`button_submit`, `textbox_email`)
- **Required Properties**: `type` for all components, `id` for non-containers
- **Validation**: Strict validation against Anvil API specifications
- **Order**: Preserve existing component order when updating forms

### Modern vs Legacy Patterns
- **Prefer**: Material 3 components (`role: outlined-card`, `role: primary-color`)
- **Use**: Reactive data bindings with `writeback: true` for model integration
- **Implement**: Proper event handler mapping to existing form methods
- **Support**: Custom components with `form:DEPENDENCY_ID:MODULE_PATH.COMPONENT_NAME`

### Model Classes
```python
@anvil.server.model_class
class User:
    name = field(String)
    email = field(String, unique=True)
    created_at = field(DateTime, default=lambda: datetime.now())
    is_active = field(Boolean, default=True)
    profile = field(Link("UserProfile", optional=True))
```

### Reactive Components
```python
@reactive_class
class UserDashboard(UserDashboardTemplate):
    def __init__(self, routing_context, **properties):
        self.user = reactive_instance(User.get_by_id(user_id))
        self.notifications = signal([])
        self.init_components(**properties)
    
    @render_effect
    def sync_user_display(self):
        bind(self.user_name, "text", lambda: self.user.name)
```

## Documentation Standards

### Code Comments
- **Minimal**: Comments should only be used when absolutely necessary
- **Prefer**: Self-documenting code through clear naming and structure
- **Use**: Docstrings for public APIs, function parameters, return values
- **Check**: Always check before adding comments

### Docstring Format
```python
def function_name(param1: str, param2: int) -> bool:
    """Brief description of function purpose.
    
    Args:
        param1: Description of first parameter
        param2: Description of second parameter
        
    Returns:
        Description of return value
        
    Raises:
        SpecificError: When error occurs
    """
```

## File Organization

### Module Structure
- **Imports**: At top, grouped by type
- **Constants**: After imports, before classes
- **Classes**: Main functionality
- **Functions**: Utility functions
- **Main**: Entry point (if applicable)

### Package Structure
- **`__init__.py`**: Package exports and version
- **Core modules**: Main functionality
- **Utility modules**: Helper functions
- **Test modules**: Comprehensive test coverage

## Quality Standards

### Code Quality
- **Clean Code**: Self-documenting, clear structure
- **Performance**: Optimal patterns without premature optimization
- **Security**: No hardcoded secrets, proper validation
- **Maintainability**: Easy to understand and modify

### Validation
- **Component Types**: Strict validation against Anvil API
- **YAML Syntax**: Proper structure and meaningful error messages
- **Python Syntax**: Comprehensive syntax checking
- **Naming Conflicts**: Prevention of identifier collisions

## Error Handling

### Exception Patterns
- **Specific Exceptions**: Use appropriate exception types
- **Context**: Provide meaningful error messages
- **Logging**: Proper error logging for debugging
- **Recovery**: Graceful handling where possible

### Validation Patterns
- **Input Validation**: Validate all external inputs
- **Type Checking**: Use type hints and runtime validation
- **Boundary Conditions**: Handle edge cases appropriately
- **User Feedback**: Clear error messages for users