# Code Documentation

## Project Structure

```
thrillwiki/
├── accounts/          # User management
├── analytics/         # Usage tracking
├── companies/         # Company profiles
├── core/             # Core functionality
├── designers/        # Designer profiles
├── email_service/    # Email handling
├── history/          # Historical views
├── history_tracking/ # Change tracking
├── location/         # Geographic features
├── media/           # Media management
├── moderation/      # Content moderation
├── parks/           # Park management
├── reviews/         # Review system
└── rides/           # Ride management
```

## Code Patterns

### 1. Model Patterns

#### History Tracking
```python
@pghistory.track()
class TrackedModel(models.Model):
    """Base class for models with history tracking"""
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
```

#### Slug Management
```python
class SluggedModel:
    """Pattern for models with slug-based URLs"""
    @classmethod
    def get_by_slug(cls, slug: str) -> Tuple[Model, bool]:
        # Check current slugs
        try:
            return cls.objects.get(slug=slug), False
        except cls.DoesNotExist:
            # Check historical slugs
            historical = HistoricalSlug.objects.filter(
                content_type=ContentType.objects.get_for_model(cls),
                slug=slug
            ).first()
            if historical:
                return cls.objects.get(pk=historical.object_id), True
```

#### Generic Relations
```python
# Example from parks/models.py
class Park(TrackedModel):
    location = GenericRelation(Location)
    photos = GenericRelation(Photo)
```

### 2. View Patterns

#### Class-Based Views
```python
class ModeratedCreateView(LoginRequiredMixin, CreateView):
    """Base view for content requiring moderation"""
    def form_valid(self, form):
        obj = form.save(commit=False)
        obj.status = 'PENDING'
        obj.created_by = self.request.user
        return super().form_valid(form)
```

#### Permission Mixins
```python
class ModeratorRequiredMixin:
    """Ensures user has moderation permissions"""
    def dispatch(self, request, *args, **kwargs):
        if not request.user.has_perm('moderation.can_moderate'):
            raise PermissionDenied
        return super().dispatch(request, *args, **kwargs)
```

### 3. Service Patterns

#### Email Service
```python
class EmailService:
    """Handles email templating and sending"""
    def send_moderation_notification(self, content):
        template = 'moderation/email/notification.html'
        context = {'content': content}
        self.send_templated_email(template, context)
```

#### Media Processing
```python
class MediaProcessor:
    """Handles image optimization and processing"""
    def process_image(self, image):
        # Optimize size
        # Extract EXIF
        # Generate thumbnails
        return processed_image
```

## Dependencies

### Core Dependencies
```toml
# From pyproject.toml
[tool.poetry.dependencies]
django = "5.1.6"
djangorestframework = "3.15.2"
django-allauth = "65.4.1"
psycopg2-binary = "2.9.10"
django-pghistory = "3.5.2"
```

### Frontend Dependencies
```json
{
    "tailwindcss": "^3.0.0",
    "htmx": "^1.22.0",
    "webpack": "^5.0.0"
}
```

## Build Configuration

### Django Settings
```python
INSTALLED_APPS = [
    # Django apps
    'django.contrib.admin',
    'django.contrib.auth',
    
    # Third-party apps
    'allauth',
    'rest_framework',
    'corsheaders',
    
    # Local apps
    'parks.apps.ParksConfig',
    'rides.apps.RidesConfig',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
]
```

### Database Configuration
```python
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': env('DB_NAME'),
        'USER': env('DB_USER'),
        'PASSWORD': env('DB_PASSWORD'),
        'HOST': env('DB_HOST'),
        'PORT': env('DB_PORT'),
    }
}
```

## Testing Framework

### Test Structure
```
tests/
├── unit/              # Unit tests
├── integration/       # Integration tests
└── e2e/              # End-to-end tests
```

### Test Patterns
```python
class ParkTestCase(TestCase):
    def setUp(self):
        self.park = Park.objects.create(
            name="Test Park",
            status="OPERATING"
        )
    
    def test_park_creation(self):
        self.assertEqual(self.park.slug, "test-park")
```

## Package Management

### Python Dependencies
```bash
# Development dependencies
pip install -r requirements-dev.txt

# Production dependencies
pip install -r requirements.txt
```

### Frontend Build
```bash
# Install frontend dependencies
npm install

# Build static assets
npm run build
```

## Code Quality Tools

### Python Tools
- black (code formatting)
- flake8 (linting)
- mypy (type checking)
- pytest (testing)

### Configuration Files
```toml
# pyproject.toml
[tool.black]
line-length = 88
target-version = ['py311']

[tool.mypy]
plugins = ["mypy_django_plugin.main"]
```

## Development Workflow

### Local Development
1. Set up virtual environment
2. Install dependencies
3. Run migrations
4. Start development server

```bash
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
python manage.py migrate
python manage.py runserver
```

### Code Review Process
1. Run linting tools
2. Run test suite
3. Check type hints
4. Review documentation

## Deployment Process

### Pre-deployment Checks
1. Run test suite
2. Check migrations
3. Validate static files
4. Verify environment variables

### Deployment Steps
1. Update dependencies
2. Apply migrations
3. Collect static files
4. Restart application server

## Error Handling

### Exception Pattern
```python
class CustomException(Exception):
    """Base exception for application"""
    def __init__(self, message, code=None):
        self.message = message
        self.code = code
```

### Middleware Pattern
```python
class ErrorHandlingMiddleware:
    """Centralized error handling"""
    def process_exception(self, request, exception):
        # Log exception
        # Handle gracefully
        # Return appropriate response