# ThrillWiki Django Backend

## 🚀 Overview

This is the Django REST API backend for ThrillWiki, replacing the previous Supabase backend. Built with modern Django best practices and production-ready packages.

## 📦 Tech Stack

- **Framework**: Django 4.2 LTS
- **API**: django-ninja (FastAPI-style)
- **Database**: PostgreSQL 15+
- **Cache**: Redis + django-cacheops
- **Tasks**: Celery + Redis
- **Real-time**: Django Channels + WebSockets
- **Auth**: django-allauth + django-otp
- **Storage**: CloudFlare Images
- **Monitoring**: Sentry + structlog

## 🏗️ Project Structure

```
django/
├── manage.py
├── config/                 # Django settings
├── apps/                   # Django applications
│   ├── core/              # Base models & utilities
│   ├── entities/          # Parks, Rides, Companies
│   ├── moderation/        # Content moderation system
│   ├── versioning/        # Entity versioning
│   ├── users/             # User management
│   ├── media/             # Image/photo management
│   └── notifications/     # Notification system
├── api/                   # REST API layer
└── scripts/               # Utility scripts
```

## 🛠️ Setup

### Prerequisites

- Python 3.11+
- PostgreSQL 15+
- Redis 7+

### Installation

```bash
# 1. Create virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# 2. Install dependencies
pip install -r requirements/local.txt

# 3. Set up environment variables
cp .env.example .env
# Edit .env with your configuration

# 4. Run migrations
python manage.py migrate

# 5. Create superuser
python manage.py createsuperuser

# 6. Run development server
python manage.py runserver
```

### Running Services

```bash
# Terminal 1: Django dev server
python manage.py runserver

# Terminal 2: Celery worker
celery -A config worker -l info

# Terminal 3: Celery beat (periodic tasks)
celery -A config beat -l info

# Terminal 4: Flower (task monitoring)
celery -A config flower
```

## 📚 Documentation

- **Migration Plan**: See `MIGRATION_PLAN.md` for full migration details
- **Architecture**: See project documentation in `/docs/`
- **API Docs**: Available at `/api/docs` when server is running

## 🧪 Testing

```bash
# Run all tests
pytest

# Run with coverage
pytest --cov=apps --cov-report=html

# Run specific app tests
pytest apps/moderation/

# Run specific test file
pytest apps/moderation/tests/test_services.py -v
```

## 📋 Key Features

### Moderation System
- State machine workflow with django-fsm
- Atomic transaction handling
- Selective approval support
- Automatic lock/unlock mechanism
- Real-time queue updates

### Versioning System
- Automatic version tracking with django-lifecycle
- Full change history for all entities
- Diff generation
- Rollback capability

### Authentication
- JWT-based API authentication
- OAuth2 (Google, Discord)
- Two-factor authentication (TOTP)
- Role-based permissions

### Performance
- Automatic query caching with django-cacheops
- Redis-based session storage
- Optimized database queries
- Background task processing with Celery

## 🔧 Management Commands

```bash
# Create test data
python manage.py seed_data

# Export data from Supabase
python manage.py export_supabase_data

# Import data to Django
python manage.py import_supabase_data

# Update cached counts
python manage.py update_counts

# Clean old data
python manage.py cleanup_old_data
```

## 🚀 Deployment

### Docker

```bash
# Build image
docker build -t thrillwiki-backend .

# Run with docker-compose
docker-compose up -d
```

### Production Checklist

- [ ] Set `DEBUG=False` in production
- [ ] Configure `ALLOWED_HOSTS`
- [ ] Set strong `SECRET_KEY`
- [ ] Configure PostgreSQL connection
- [ ] Set up Redis
- [ ] Configure Celery workers
- [ ] Set up SSL/TLS
- [ ] Configure CORS origins
- [ ] Set up Sentry for error tracking
- [ ] Configure CloudFlare Images
- [ ] Set up monitoring/logging

## 📊 Development Status

**Current Phase**: Foundation  
**Branch**: `django-backend`

### Completed
- ✅ Project structure created
- ✅ Dependencies installed
- ✅ Environment configuration

### In Progress
- 🔄 Django settings configuration
- 🔄 Base models creation
- 🔄 Database connection setup

### Upcoming
- ⏳ Entity models implementation
- ⏳ Authentication system
- ⏳ Moderation system
- ⏳ API layer with django-ninja

See `MIGRATION_PLAN.md` for detailed roadmap.

## 🤝 Contributing

1. Create a feature branch from `django-backend`
2. Make your changes
3. Write/update tests
4. Run test suite
5. Submit pull request

## 📝 Environment Variables

Required environment variables (see `.env.example`):

```bash
# Django
DEBUG=True
SECRET_KEY=your-secret-key
ALLOWED_HOSTS=localhost

# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/thrillwiki

# Redis
REDIS_URL=redis://localhost:6379/0

# External Services
CLOUDFLARE_ACCOUNT_ID=xxx
CLOUDFLARE_IMAGE_TOKEN=xxx
NOVU_API_KEY=xxx
SENTRY_DSN=xxx

# OAuth
GOOGLE_CLIENT_ID=xxx
GOOGLE_CLIENT_SECRET=xxx
DISCORD_CLIENT_ID=xxx
DISCORD_CLIENT_SECRET=xxx
```

## 🐛 Troubleshooting

### Database Connection Issues
```bash
# Check PostgreSQL is running
pg_isready

# Verify connection string
python manage.py dbshell
```

### Celery Not Processing Tasks
```bash
# Check Redis is running
redis-cli ping

# Restart Celery worker
celery -A config worker --purge -l info
```

### Import Errors
```bash
# Ensure virtual environment is activated
which python  # Should point to venv/bin/python

# Reinstall dependencies
pip install -r requirements/local.txt --force-reinstall
```

## 📞 Support

- **Documentation**: See `/docs/` directory
- **Issues**: GitHub Issues
- **Migration Questions**: See `MIGRATION_PLAN.md`

## 📄 License

Same as main ThrillWiki project.

---

**Last Updated**: November 8, 2025  
**Status**: Foundation Phase - Active Development
