# API Reference

## Authentication Endpoints

### POST /api/auth/register
Register a new user.

**Request:**
```json
{
    "email": "user@example.com",
    "password": "password123"
}
```

**Response (Success - 200):**
```json
{
    "success": true,
    "user": {
        "id": 1,
        "email": "user@example.com",
        "token": "hex_token_string"
    }
}
```

**Response (Error - 400):**
```json
{
    "success": false,
    "error": "Email already registered"
}
```

---

### POST /api/auth/login
Login existing user.

**Request:**
```json
{
    "email": "user@example.com",
    "password": "password123"
}
```

**Response (Success - 200):**
```json
{
    "success": true,
    "user": {
        "id": 1,
        "email": "user@example.com",
        "token": "hex_token_string"
    }
}
```

**Response (Error - 401):**
```json
{
    "success": false,
    "error": "Invalid email or password"
}
```

---

### GET /api/auth/logout
Logout current user.

**Response (Success - 200):**
```json
{
    "success": true
}
```

---

## Game Endpoints

### POST /api/game/generation
Generate initial tribe setup (20 random kobolds).

**Request:**
```json
{
    "userId": 1,
    "saveName": "My Tribe"
}
```

**Response (Success - 200):**
```json
{
    "success": true,
    "save": {
        "id": 1,
        "name": "My Tribe"
    },
    "kobolds": [
        {
            "id": 1,
            "age": 15,
            "stats": {
                "vitality": 45,
                "intelligence": 52,
                "medicine": 42,
                "crafting": 61,
                "personality": 48,
                "will": 55
            }
        }
    ]
}
```

---

### GET /api/game/list
List all saves for user.

**Headers:**
```
Authorization: Bearer {token}
```

**Response (Success - 200):**
```json
{
    "success": true,
    "saves": [
        {
            "id": 1,
            "name": "My Tribe",
            "current_month": 5,
            "current_season": "summer",
            "last_played": "2024-01-27 10:30:00"
        }
    ]
}
```

---

### GET /api/game/load
Load a specific save.

**Parameters:**
```
saveId=1
```

**Headers:**
```
Authorization: Bearer {token}
```

**Response (Success - 200):**
```json
{
    "success": true,
    "save": {
        "id": 1,
        "name": "My Tribe",
        "current_month": 5,
        "current_season": "summer"
    },
    "tribe": {
        "kobolds": [
            {
                "id": 1,
                "name": "Zyx",
                "age": 25,
                "ageCategory": "adult"
            }
        ]
    }
}
```

---

### POST /api/game/save
Save tribe setup after kobold selection.

**Request:**
```json
{
    "saveId": 1,
    "leaderName": "Zyx",
    "memberIndices": [1, 2, 3, 4, 5]
}
```

**Response (Success - 200):**
```json
{
    "success": true,
    "tribe": {}
}
```

---

### POST /api/game/event
Execute a player-initiated event.

**Request:**
```json
{
    "saveId": 1,
    "eventType": "hunting"
}
```

**Response (Success - 200):**
```json
{
    "success": true,
    "story": "The hunting party set out into the wilderness...\n\nThe hunters returned with valuable supplies."
}
```

---

### POST /api/game/endMonth
End the current month and progress the game.

**Request:**
```json
{
    "saveId": 1
}
```

**Response (Success - 200):**
```json
{
    "success": true,
    "save": {
        "id": 1,
        "current_month": 6,
        "current_season": "summer"
    },
    "monthStory": "The month passed without major incident.\n\nZyx has grown older and wiser."
}
```

---

## Error Responses

### 400 Bad Request
```json
{
    "success": false,
    "error": "Description of what went wrong"
}
```

### 401 Unauthorized
```json
{
    "success": false,
    "error": "Not authenticated"
}
```

### 404 Not Found
```json
{
    "error": "Not found"
}
```

---

## Frontend Usage Example

```javascript
// Registration
const response = await fetch('/api/auth/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ 
        email: 'user@example.com', 
        password: 'pass123' 
    })
});
const data = await response.json();

// Use token for authenticated requests
const gameResponse = await fetch('/api/game/list', {
    method: 'GET',
    headers: { 'Authorization': `Bearer ${data.user.token}` }
});
```

---

## Stat Values Reference

All stats are 0-100 internally but displayed as:

| Range | Label |
|-------|-------|
| 0-10 | terrible |
| 10-20 | bad |
| 20-30 | unskilled |
| 30-40 | decent |
| 40-50 | good |
| 50-60 | excellent |
| 60-70 | fantastic |
| 70-80 | master |
| 80-90 | divine |
| 90-100 | godlike |

---

## Age Categories Reference

| Category | Age Range | Stat Scaling |
|----------|-----------|--------------|
| egg | < 0 | 0% |
| baby | 0-3 | 0-100% progression |
| adult | 4-34 | 100% |
| old | 35-59 | 100% + injuries |
| very_old | 60+ | 100% + many injuries |

---

## Data Types

### Kobold Object
```php
[
    'id' => int,
    'saveId' => int,
    'name' => string,
    'age' => int (0-100),
    'stats' => [
        'vitality' => int (0-100),
        'intelligence' => int (0-100),
        'medicine' => int (0-100),
        'crafting' => int (0-100),
        'personality' => int (0-100),
        'will' => int (0-100)
    ],
    'spriteMorph' => string,
    'isLeader' => bool,
    'isAlive' => bool,
    'injuries' => [
        [
            'id' => int,
            'injuryType' => string,
            'category' => string,
            'severity' => int (0-10)
        ]
    ],
    'items' => [
        [
            'id' => int,
            'name' => string,
            'description' => string,
            'itemType' => string,
            'modifications' => ['stat_name' => int]
        ]
    ]
]
```

### Tribe Object
```php
[
    'id' => int,
    'name' => string,
    'currentMonth' => int,
    'currentSeason' => string (spring|summer|autumn|winter),
    'kobolds' => [Kobold, ...],
    'storage' => [Item, ...]
]
```

### Save Object
```php
[
    'id' => int,
    'userId' => int,
    'name' => string,
    'currentMonth' => int,
    'currentSeason' => string,
    'createdAt' => datetime,
    'lastPlayed' => datetime
]
```

---

## HTTP Status Codes

| Code | Meaning |
|------|---------|
| 200 | Success |
| 400 | Bad request / validation error |
| 401 | Unauthorized / not authenticated |
| 404 | Not found |
| 500 | Server error |

---

## Rate Limiting

Currently none implemented. Add if needed for production.

---

## CORS

CORS is not enabled by default. Configure if needed for cross-origin requests.

---

## Authentication

Use the token from login/register response in the `Authorization: Bearer` header for all subsequent requests that require authentication.

Tokens are stored in browser localStorage and should be cleared on logout.

---

## Pagination

Not currently implemented. Can be added to the game/list endpoint if needed for large numbers of saves.
