# Contributing to Stiftung Application

Thank you for your interest in contributing! This guide will help you get started with development and ensure consistency across the project.

## 🚀 Quick Start

### 1. Development Environment Setup

```bash
# Clone the repository
git clone https://github.com/yourusername/stiftung-starter.git
cd stiftung-starter

# Run setup script
chmod +x scripts/dev-setup.sh
./scripts/dev-setup.sh

# Or manual setup:
cp env-template.txt .env
docker-compose up -d
docker-compose exec web python manage.py migrate
docker-compose exec web python manage.py createsuperuser
```

### 2. Verify Installation

- Application: http://localhost:8000
- Admin: http://localhost:8000/admin/
- HelpBox Admin: http://localhost:8000/help-box/admin/

## 🔄 Development Workflow

### Using the Git Workflow Helper

```bash
chmod +x scripts/git-workflow.sh
./scripts/git-workflow.sh
```

### Manual Workflow

1. **Create Feature Branch**
   ```bash
   git checkout main
   git pull origin main
   git checkout -b feature/your-feature-name
   ```

2. **Make Changes**
   - Follow coding standards (see below)
   - Add tests for new functionality
   - Update documentation if needed

3. **Test Your Changes**
   ```bash
   # Run tests
   docker-compose exec web python manage.py test
   
   # Check Django configuration
   docker-compose exec web python manage.py check
   
   # Test migrations
   docker-compose exec web python manage.py migrate --dry-run
   ```

4. **Commit Changes**
   ```bash
   git add .
   git commit -m "feat: describe your changes"
   ```

5. **Push and Create PR**
   ```bash
   git push origin feature/your-feature-name
   # Create Pull Request on GitHub
   ```

## 📝 Coding Standards

### Python/Django Code

- **PEP 8 compliance**: Use `black` and `flake8`
- **Import sorting**: Use `isort`
- **Docstrings**: Document all classes and methods
- **Type hints**: Use type annotations where possible

```python
# Example: Good code style
from typing import Optional, List
from django.db import models

class HelpBox(models.Model):
    """Editable help boxes with Markdown support."""
    
    title: str = models.CharField(max_length=200)
    content: str = models.TextField()
    
    def get_rendered_content(self) -> str:
        """Render Markdown content to HTML."""
        return markdown.markdown(self.content)
    
    @classmethod
    def get_help_for_page(cls, page_key: str) -> Optional['HelpBox']:
        """Get active help box for a specific page."""
        return cls.objects.filter(
            page_key=page_key, 
            is_active=True
        ).first()
```

### HTML/Templates

- **Bootstrap 5**: Use consistent Bootstrap classes
- **Template inheritance**: Extend `base.html`
- **Template tags**: Create reusable components
- **Accessibility**: Include ARIA labels and alt text

```html
<!-- Example: Good template structure -->
{% extends "base.html" %}
{% load help_tags %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-lg-8">
            <!-- Main content -->
            <form method="post">
                {% csrf_token %}
                {{ form.as_p }}
                <button type="submit" class="btn btn-primary">Save</button>
            </form>
        </div>
        <div class="col-lg-4">
            <!-- Help box sidebar -->
            {% help_box 'page_key' user %}
        </div>
    </div>
</div>
{% endblock %}
```

### JavaScript

- **ES6+**: Use modern JavaScript features
- **No jQuery**: Use vanilla JS or minimal libraries
- **Accessibility**: Support keyboard navigation

```javascript
// Example: Good JavaScript structure
class HelpBoxEditor {
    constructor(elementId) {
        this.element = document.getElementById(elementId);
        this.init();
    }
    
    init() {
        this.element.addEventListener('click', this.handleEdit.bind(this));
    }
    
    handleEdit(event) {
        // Implementation
    }
}
```

## 🧪 Testing

### Writing Tests

```python
# Example: Test structure
from django.test import TestCase, Client
from django.contrib.auth import get_user_model
from stiftung.models import HelpBox

class HelpBoxTestCase(TestCase):
    def setUp(self):
        self.user = get_user_model().objects.create_user(
            username='testuser',
            password='testpass'
        )
        self.client = Client()
    
    def test_help_box_creation(self):
        """Test help box can be created."""
        help_box = HelpBox.objects.create(
            page_key='test_page',
            title='Test Help',
            content='# Test Content',
            created_by=self.user
        )
        self.assertEqual(help_box.title, 'Test Help')
    
    def test_help_box_rendering(self):
        """Test Markdown content is rendered correctly."""
        # Implementation
```

### Running Tests

```bash
# Run all tests
docker-compose exec web python manage.py test

# Run specific test
docker-compose exec web python manage.py test stiftung.tests.test_helpbox

# Run with coverage
docker-compose exec web coverage run manage.py test
docker-compose exec web coverage report
```

## 📦 New Feature Development

### Adding a New Model

1. Create model in `stiftung/models.py`
2. Add to Django admin in `stiftung/admin.py`
3. Create and run migrations
4. Add views in `stiftung/views.py`
5. Create templates
6. Add URL patterns
7. Write tests
8. Update documentation

### Adding HelpBox Support to New Pages

1. **Add page key to model choices:**
   ```python
   # In stiftung/models.py
   PAGE_CHOICES = [
       # ... existing choices
       ('your_new_page', 'Your New Page'),
   ]
   ```

2. **Add template tag to your template:**
   ```html
   {% load help_tags %}
   {% help_box 'your_new_page' user %}
   ```

3. **Create migration and test:**
   ```bash
   docker-compose exec web python manage.py makemigrations
   docker-compose exec web python manage.py migrate
   ```

## 🎨 UI/UX Guidelines

### Bootstrap Usage

- Use Bootstrap 5 utility classes
- Follow responsive design principles
- Maintain consistent spacing (mb-3, p-4, etc.)
- Use semantic HTML elements

### Color Scheme

- Primary: Bootstrap primary blue
- Success: Bootstrap success green
- Warning: Bootstrap warning yellow
- Danger: Bootstrap danger red

### Icons

- Use Bootstrap Icons or Font Awesome
- Consistent icon usage across features
- Include alt text for accessibility

## 📊 Database Changes

### Migration Best Practices

1. **Always create migrations:**
   ```bash
   docker-compose exec web python manage.py makemigrations
   ```

2. **Review migration files before committing**

3. **Test migrations on production-like data:**
   ```bash
   docker-compose exec web python manage.py migrate --dry-run
   ```

4. **Provide data migration scripts when needed**

### Model Changes

- Use descriptive field names
- Add help_text for complex fields
- Consider backward compatibility
- Document breaking changes

## 🚢 Deployment Considerations

### Production Checklist

- [ ] All tests pass
- [ ] Migrations run successfully
- [ ] Static files collect properly
- [ ] Environment variables configured
- [ ] Security settings reviewed
- [ ] Performance impact assessed

### Docker Best Practices

- Keep Dockerfile lean
- Use multi-stage builds when possible
- Don't include secrets in images
- Use .dockerignore effectively

## 📖 Documentation

### Code Documentation

- Document all public methods
- Include usage examples
- Explain complex business logic
- Update docstrings when changing behavior

### User Documentation

- Update README for new features
- Add screenshots for UI changes
- Document configuration options
- Provide troubleshooting guides

## 🐛 Bug Reports

### Bug Report Template

```markdown
**Describe the bug**
A clear description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. See error

**Expected behavior**
What you expected to happen.

**Screenshots**
If applicable, add screenshots.

**Environment:**
- OS: [e.g. Windows 10]
- Browser: [e.g. Chrome 96]
- Version: [e.g. v2.0.0]

**Additional context**
Any other context about the problem.
```

## 🔍 Code Review Guidelines

### For Authors

- Keep PRs focused and small
- Write descriptive commit messages
- Test thoroughly before submitting
- Update documentation as needed

### For Reviewers

- Review for functionality, security, and performance
- Check code style and conventions
- Verify tests are adequate
- Provide constructive feedback

## 🎯 Feature Requests

### Feature Request Template

```markdown
**Is your feature request related to a problem?**
A clear description of what the problem is.

**Describe the solution you'd like**
A clear description of what you want to happen.

**Describe alternatives you've considered**
Other solutions you've considered.

**Additional context**
Screenshots, mockups, or examples.
```

## 💬 Getting Help

- Create GitHub Issues for bugs
- Use GitHub Discussions for questions
- Check existing documentation first
- Provide minimal reproduction examples

## 📜 License

By contributing, you agree that your contributions will be licensed under the same license as the project.
