# CLAUDE.md - API Backend

## Service Overview
**API Backend** for Code of Conquest - The single source of truth for all business logic, game mechanics, and data operations.

**Tech Stack:** Flask + Appwrite + RQ + Redis + Replicate API (Llama-3/Claude models)
**Port:** 5000 (development), 5000 (production internal)
**Location:** `/api`

---

## Architecture Role

This API backend is the **single source of truth** for all game logic:
- ✅ All business logic
- ✅ Data models and validation
- ✅ Database operations (Appwrite)
- ✅ Authentication & authorization
- ✅ Game mechanics calculations
- ✅ AI orchestration (all models via Replicate API)
- ✅ Background job processing (RQ)

**What this service does NOT do:**
- ❌ No UI rendering (that's `/public_web` and `/godot_client`)
- ❌ No direct user interaction (only via API endpoints)

---

## Documentation Index

**API Backend Documentation:**
- **[API_REFERENCE.md](docs/API_REFERENCE.md)** - API endpoints and response formats
- **[DATA_MODELS.md](docs/DATA_MODELS.md)** - Character system, items, skills, effects
- **[GAME_SYSTEMS.md](docs/GAME_SYSTEMS.md)** - Combat mechanics, marketplace, NPCs
- **[QUEST_SYSTEM.md](docs/QUEST_SYSTEM.md)** - Quest mechanics and data structures
- **[STORY_PROGRESSION.md](docs/STORY_PROGRESSION.md)** - Story progression system
- **[MULTIPLAYER.md](docs/MULTIPLAYER.md)** - Multiplayer session backend logic
- **[API_TESTING.md](docs/API_TESTING.md)** - API testing guide with examples
- **[APPWRITE_SETUP.md](docs/APPWRITE_SETUP.md)** - Database setup guide
- **[PHASE4_IMPLEMENTATION.md](docs/PHASE4_IMPLEMENTATION.md)** - Phase 4 detailed implementation tasks

**Project-Wide Documentation:**
- **[../docs/ARCHITECTURE.md](../docs/ARCHITECTURE.md)** - System architecture overview
- **[../docs/ROADMAP.md](../docs/ROADMAP.md)** - Development roadmap and progress tracking
- **[../docs/DEPLOYMENT.md](../docs/DEPLOYMENT.md)** - Deployment guide
- **[../docs/WEB_VS_CLIENT_SYSTEMS.md](../docs/WEB_VS_CLIENT_SYSTEMS.md)** - Feature distribution between frontends

**Documentation Hierarchy:**
- `/docs/` = Project-wide roadmap, architecture, and cross-service documentation
- `/api/docs/` = API-specific implementation details (endpoints, data models, game systems)

> **Note:** For overall project progress, always check `/docs/ROADMAP.md`. Service-specific docs contain implementation details.

---

## Development Guidelines

### Project Structure

```
api/
├── app/                    # Application code
│   ├── api/               # API endpoint blueprints
│   ├── models/            # Data models (dataclasses)
│   ├── services/          # Business logic & integrations
│   ├── utils/             # Utilities
│   ├── tasks/             # Background jobs (RQ)
│   ├── ai/                # AI integration
│   ├── game_logic/        # Game mechanics
│   └── data/              # Game data (YAML)
├── config/                # Configuration files
├── tests/                 # Test suite
├── scripts/               # Utility scripts
└── docs/                  # API documentation
```

### Coding Standards

**Style & Structure**
- Prefer longer, explicit code over compact one-liners
- Always include docstrings for functions/classes + inline comments
- Strongly prefer OOP-style code (classes over functional/nested functions)
- Strong typing throughout (dataclasses, TypedDict, Enums, type hints)
- Value future-proofing and expanded usage insights

**Data Design**
- Use dataclasses for internal data modeling
- Typed JSON structures
- Functions return fully typed objects (no loose dicts)
- Snapshot files in JSON or YAML
- Human-readable fields (e.g., `scan_duration`)

**Logging**
- Use structlog (pip package)
- Setup logging at app start: `logger = structlog.get_logger(__file__)`

**Preferred Pip Packages**
- API/Web Server: Flask
- HTTP: Requests
- Logging: Structlog
- Job Queue: RQ
- Testing: Pytest

### API Design Standards

**RESTful Conventions:**
- Use proper HTTP methods (GET, POST, PUT, DELETE)
- Resource-based URLs: `/api/v1/characters`, not `/api/v1/get_character`
- Versioning: `/api/v1/...`

**Standardized Response Format:**
```json
{
  "app": "Code of Conquest API",
  "version": "0.1.0",
  "status": 200,
  "timestamp": "2025-01-15T10:30:00Z",
  "request_id": "optional-request-id",
  "result": {
    "data": "..."
  },
  "error": null,
  "meta": {}
}
```

**Error Responses:**
```json
{
  "app": "Code of Conquest API",
  "version": "0.1.0",
  "status": 400,
  "timestamp": "2025-01-15T10:30:00Z",
  "result": null,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid character name",
    "details": {
      "field": "name",
      "issue": "Name must be between 3 and 50 characters"
    }
  }
}
```

### Error Handling
- Custom exception classes for domain-specific errors
- Consistent error response formats (use `app.utils.response`)
- Logging severity levels (ERROR vs WARNING)
- Never expose internal errors to clients (sanitize stack traces)

### Security Standards

**Authentication & Authorization**
- Use Appwrite Auth for user management
- HTTP-only cookies for session storage
- Session validation on every protected API call
- User ID verification (users can only access their own data)
- Use `@require_auth` decorator for protected endpoints

**Input Validation**
- Validate ALL JSON payloads against schemas
- Sanitize user inputs (character names, chat messages)
- Prevent injection attacks (SQL, NoSQL, command injection)
- Use bleach for HTML sanitization

**Rate Limiting**
- AI endpoint limits based on subscription tier
- Use Flask-Limiter with Redis backend
- Configure limits in `config/*.yaml`

**API Security**
- CORS properly configured (only allow frontend domains)
- API keys stored in environment variables (never in code)
- Appwrite permissions set correctly on all collections
- HTTPS only in production

**Cost Control (AI)**
- Daily limits on AI calls per tier
- Max tokens per request type
- Cost logging for analytics and alerts
- Graceful degradation if limits exceeded

### Configuration
- Environment-specific configs in `/config/*.yaml`
  - `development.yaml` - Local dev settings
  - `production.yaml` - Production settings
- `.env` for secrets (never committed)
- Maintain `.env.example` for documentation
- Typed config loaders using dataclasses
- Validation on startup

### Testing Standards

**Unit Tests (Pytest):**
- Test all models, services, game logic
- Test files in `/tests`
- Run with: `pytest`
- Coverage: `pytest --cov=app tests/`

**Integration Tests:**
- Test API endpoints end-to-end
- Use test database/fixtures
- Example: `tests/test_api_characters_integration.py`

**API Testing:**
- Maintain `docs/API_TESTING.md` with curl/httpie examples
- Document expected responses
- Test all endpoints manually before commit

### Dependency Management
- Use `requirements.txt` in `/api` directory
- Use virtual environment: `python3 -m venv venv`
- Pin versions to version ranges
- Activate venv before running: `source venv/bin/activate`

### Background Jobs (RQ)

**Queue Types:**
- `ai_tasks` - AI narrative generation
- `combat_tasks` - Combat processing
- `marketplace_tasks` - Auction cleanup, periodic tasks

**Job Implementation:**
- Define jobs in `app/tasks/`
- Use `@job` decorator from RQ
- Jobs should be idempotent (safe to retry)
- Log job start, completion, errors

**Running Workers:**
```bash
rq worker ai_tasks combat_tasks marketplace_tasks --url redis://localhost:6379
```

---

## Workflow for API Development

When implementing new API features:

1. **Start with models** - Define dataclasses in `app/models/`
2. **Write tests** - TDD approach (test first, then implement)
3. **Implement service** - Business logic in `app/services/`
4. **Create endpoint** - API blueprint in `app/api/`
5. **Test manually** - Use curl/httpie, update `docs/API_TESTING.md`
6. **Security review** - Check auth, validation, rate limiting
7. **Document** - Update `docs/API_REFERENCE.md`

**Example Flow:**
```bash
# 1. Create model
# app/models/quest.py - Define Quest dataclass

# 2. Write test
# tests/test_quest.py - Test quest creation, validation

# 3. Implement service
# app/services/quest_service.py - Quest CRUD operations

# 4. Create endpoint
# app/api/quests.py - REST endpoints

# 5. Test
curl -X POST http://localhost:5000/api/v1/quests \
  -H "Content-Type: application/json" \
  -d '{"title": "Find the Ancient Relic"}'

# 6. Document
# Update docs/API_REFERENCE.md and docs/API_TESTING.md
```

---

## Running the API Backend

### Development

**Prerequisites:**
- Python 3.11+
- Redis running (via Docker Compose)
- Appwrite instance configured

**Setup:**
```bash
cd api
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
cp .env.example .env
# Edit .env with your credentials
```

**Initialize Database:**
```bash
python scripts/init_database.py
```

**Run Development Server:**
```bash
# Terminal 1: Redis
docker-compose up

# Terminal 2: API Server
source venv/bin/activate
export FLASK_ENV=development
python wsgi.py  # → http://localhost:5000

# Terminal 3: RQ Worker (optional)
source venv/bin/activate
rq worker ai_tasks --url redis://localhost:6379
```

### Production

**Run with Gunicorn:**
```bash
gunicorn --bind 0.0.0.0:5000 --workers 4 wsgi:app
```

**Environment Variables:**
```
FLASK_ENV=production
APPWRITE_ENDPOINT=https://cloud.appwrite.io/v1
APPWRITE_PROJECT_ID=...
APPWRITE_API_KEY=...
APPWRITE_DATABASE_ID=...
ANTHROPIC_API_KEY=...
REPLICATE_API_TOKEN=...
REDIS_URL=redis://redis:6379
SECRET_KEY=...
```

---

## Git Standards

**Commit Messages:**
- Use conventional commit format: `feat:`, `fix:`, `docs:`, `refactor:`, etc.
- Examples:
  - `feat(api): add quest endpoints`
  - `fix(models): character stat calculation bug`
  - `docs(api): update API_REFERENCE with quest endpoints`

**Branch Strategy:**
- Branch off `dev` for features
- Merge back to `dev` for testing
- Promote to `master` for production

---

## Notes for Claude Code

When working on the API backend:

1. **Business logic lives here** - This is the single source of truth
2. **No UI code** - Don't create templates or frontend code in this service
3. **Security first** - Validate inputs, check permissions, sanitize outputs
4. **Cost conscious** - Monitor AI usage, implement limits
5. **Test thoroughly** - Use pytest, write integration tests
6. **Document as you go** - Update API_REFERENCE.md and API_TESTING.md
7. **Think about frontends** - Design endpoints that work for both web and Godot clients

**Remember:**
- Developer has strong security expertise (don't compromise security for convenience)
- Developer has extensive infrastructure experience (focus on application logic)
- This API serves multiple frontends (web and Godot) - keep it generic
