# Environment-Specific Details & Gotchas

**Last Updated**: 2025-10-21

This document contains critical environment-specific configurations and common pitfalls to avoid.

## System Information

- **OS**: Linux (Nobara Fedora 42)
- **Python**: 3.13.3
- **Docker**: Compose V2 (use `docker compose` not `docker-compose`)
- **Database Server**: 10.10.0.42:5432 (PostgreSQL)

## Critical Gotchas

### 1. Docker Compose Command
❌ **WRONG**: `docker-compose up -d`
✅ **CORRECT**: `docker compose up -d`

This system uses Docker Compose V2. The legacy `docker-compose` command does not exist.

### 2. Pendulum for ALL DateTime Operations
❌ **NEVER DO THIS**:
```python
from datetime import datetime
now = datetime.utcnow()  # DEPRECATED & WRONG
```

✅ **ALWAYS DO THIS**:
```python
import pendulum
now = pendulum.now('UTC')
```

**Reason**: We standardized on Pendulum for better timezone handling and to avoid deprecated Python datetime methods.

### 3. SQLAlchemy Reserved Column Names
❌ **THESE WILL FAIL**:
```python
class MyModel(Base):
    metadata = Column(JSON)      # RESERVED
    registry = Column(String)    # RESERVED
    __mapper__ = Column(String)  # RESERVED
```

✅ **USE DESCRIPTIVE NAMES**:
```python
class MyModel(Base):
    game_metadata = Column(JSON)
    user_registry = Column(String)
    mapper_data = Column(String)
```

### 4. Pydantic Settings List Format
❌ **WRONG** (.env file):
```bash
CORS_ORIGINS=http://localhost:3000,http://localhost:3001
```

✅ **CORRECT** (.env file):
```bash
CORS_ORIGINS=["http://localhost:3000", "http://localhost:3001"]
```

**Reason**: Pydantic Settings expects JSON format for list types.

### 5. AsyncPG Requires Greenlet
If you see this error:
```
ValueError: the greenlet library is required to use this function
```

**Solution**: Install greenlet explicitly:
```bash
pip install greenlet
```

This is needed for SQLAlchemy's async support with asyncpg.

## Database Configuration

### Development Database
- **Host**: `10.10.0.42`
- **Port**: `5432`
- **Database**: `paperdynasty_dev`
- **User**: `paperdynasty`
- **Connection String**: `postgresql+asyncpg://paperdynasty:PASSWORD@10.10.0.42:5432/paperdynasty_dev`

### Creating the Database (if needed)
```sql
-- On PostgreSQL server (via Adminer or psql)
CREATE DATABASE paperdynasty_dev;
CREATE USER paperdynasty WITH PASSWORD 'your-password';
GRANT ALL PRIVILEGES ON DATABASE paperdynasty_dev TO paperdynasty;

-- After connecting to paperdynasty_dev
GRANT ALL ON SCHEMA public TO paperdynasty;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO paperdynasty;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO paperdynasty;
```

### Production Database
- **Host**: TBD
- **Database**: `paperdynasty_prod`
- Use different, secure credentials

## Package Versions

Due to Python 3.13 compatibility, we use newer versions than originally specified:

| Package | Original | Updated | Reason |
|---------|----------|---------|--------|
| fastapi | 0.104.1 | 0.115.6 | Python 3.13 support |
| uvicorn | 0.24.0 | 0.34.0 | Python 3.13 support |
| pydantic | 2.5.0 | 2.10.6 | Python 3.13 support |
| sqlalchemy | 2.0.23 | 2.0.36 | Python 3.13 support |
| asyncpg | 0.29.0 | 0.30.0 | Python 3.13 wheels |
| pendulum | N/A | 3.0.0 | New requirement |
| pytest | 7.4.3 | 8.3.4 | Python 3.13 support |

## Virtual Environment

### Backend
```bash
cd backend
source venv/bin/activate  # Activate
python -m app.main        # Run server
deactivate                # When done
```

### Frontends (when created)
```bash
cd frontend-sba
npm install
npm run dev

cd frontend-pd
npm install
npm run dev
```

## Server Endpoints

### Backend (Port 8000)
- **Main API**: http://localhost:8000
- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc
- **Health Check**: http://localhost:8000/api/health
- **DB Health**: http://localhost:8000/api/health/db

### Frontends (when created)
- **SBA League**: http://localhost:3000
- **PD League**: http://localhost:3001

### Services
- **Redis**: localhost:6379
- **PostgreSQL**: 10.10.0.42:5432

## Common Commands

### Backend Development
```bash
# Start Redis
docker compose up -d

# Run backend (from backend/ directory)
source venv/bin/activate
python -m app.main

# Run tests
pytest tests/ -v

# Code formatting
black app/ tests/

# Type checking
mypy app/
```

### Docker Management
```bash
# Start Redis
docker compose up -d

# Stop Redis
docker compose down

# View Redis logs
docker compose logs redis

# Check running containers
docker ps
```

## Troubleshooting

### Server Won't Start
1. Check virtual environment is activated: `which python` should show `venv/bin/python`
2. Verify .env file has correct DATABASE_URL with password
3. Ensure CORS_ORIGINS is JSON array format
4. Check PostgreSQL server is accessible: `psql postgresql://paperdynasty:PASSWORD@10.10.0.42:5432/paperdynasty_dev`

### Import Errors
1. Ensure all `__init__.py` files exist in package directories
2. Run from backend directory: `python -m app.main` not `python app/main.py`

### Database Connection Errors
1. Verify database exists: `psql -h 10.10.0.42 -U paperdynasty -d paperdynasty_dev`
2. Check firewall rules if connection times out
3. Verify credentials in .env file

### WebSocket Connection Issues
1. Check CORS_ORIGINS includes frontend URL
2. Verify JWT token is being sent from client
3. Check browser console for specific error messages

## Security Notes

- ✅ `.env` files are gitignored
- ✅ Secret key is randomly generated (32+ chars)
- ✅ Database credentials never committed to git
- ✅ JWT tokens expire after 7 days
- ✅ All WebSocket connections require authentication

## Next Steps

- [ ] Set up Discord OAuth integration
- [ ] Create frontend projects (Nuxt 3)
- [ ] Implement game engine (Phase 2)
- [ ] Add comprehensive test coverage
- [ ] Set up CI/CD pipeline

---

**Note**: Keep this document updated as new environment-specific details are discovered.
