# Architecture Overview

## Database Schema

### Users
- `id` (PK)
- `email` (UNIQUE)
- `password_hash`
- `created_at`

### Saves
- `id` (PK)
- `user_id` (FK)
- `name`
- `current_month`
- `current_season`
- `created_at`
- `last_played`

### Kobolds
- `id` (PK)
- `save_id` (FK)
- `name`
- `age`
- `vitality`, `intelligence`, `medicine`, `crafting`, `personality`, `will`
- `sprite_morph`
- `is_leader`
- `is_alive`
- `expelled`
- `father_id` (FK, self-reference)
- `mother_id` (FK, self-reference)
- `created_at`

### Injuries
- `id` (PK)
- `kobold_id` (FK)
- `injury_type` (string)
- `category` (wound, fracture, etc.)
- `severity` (0-10)
- `created_at`

### Items
- `id` (PK)
- `save_id` (FK)
- `name`
- `description`
- `item_type`
- `created_at`

### Item Modifications
- `id` (PK)
- `item_id` (FK)
- `stat_name`
- `modification` (-5 to +5)

### Kobold Items (many-to-many)
- `kobold_id` (FK)
- `item_id` (FK)

### Events Enabled
- `id` (PK)
- `save_id` (FK)
- `event_class`
- `enabled` (boolean)

### Injuries Enabled
- `id` (PK)
- `save_id` (FK)
- `injury_type`
- `enabled` (boolean)

### NPCs
- `id` (PK)
- `save_id` (FK)
- `name`
- `npc_type` (tribe, individual)
- `is_rival` (boolean)
- `data` (JSON for extensibility)
- `created_at`

## Class Hierarchy

### Core Classes
- `Database`: Singleton for SQLite access
- `User`: User authentication and save management
- `Kobold`: Individual kobold with stats, injuries, items, genetics
- `Tribe`: Collection of kobolds, tribe-level management
- `Item`: Items with stat modifications
- `Injury`: Injury tracking with severity
- `NPC`: Non-player characters/tribes

### Event System
- `Event` (abstract): Base class for all events
- `EventManager`: Manages enabled events, executes them
- Event implementations: `HuntingEvent`, `ExplorationEvent`, `FarmingEvent`, etc.

## API Flow

### Authentication
1. User registers/logs in via `/api/auth/`
2. Server returns user object with token
3. Token stored in localStorage
4. Token sent with all subsequent requests

### Game Creation
1. User submits tribe name to `/api/game/generation`
2. Server creates save record
3. Server generates 20 random kobolds
4. Returns kobold data to frontend

### Game Load
1. User clicks save to load
2. Frontend calls `/api/game/load?saveId=X`
3. Server loads tribe, kobolds, items, injuries
4. Returns complete game state

### Event Execution
1. User initiates event via `/api/game/event`
2. Server loads tribe state
3. Event modifies tribe state
4. Event returns narrative story
5. Frontend displays story in modal

### Month Progression
1. User clicks "End Month"
2. Server increments month/season
3. Kobolds age
4. Old-age injuries applied
5. Random month-progression events occur
6. Dead kobolds removed
7. Story returned to frontend

## Stat System

### Stat Ranges
All stats are 0-100 internally but displayed as text:
- 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

### Stat Checks
1. Get base stat value
2. Apply item modifications
3. Subtract injury severity total
4. For non-adults, multiply by age progress percentage
5. Clamp to 0-100
6. Roll 1d100 under stat (≤ stat = success)

### Age Progression
- Eggs and babies: effective stat = base stat × age progress (0-100%)
- At age 4 (adult): 100% effective stat
- Stats remain at full value until old age

## Event Architecture

Each event:
1. Receives the current `Tribe` object
2. Can read tribe state (kobolds, items, storage)
3. Can modify tribe state
4. Generates narrative story
5. Returns story to display

Example:
```php
class HuntingEvent extends Event {
    public function execute() {
        $this->story = "The hunters set out...";
        
        // Access tribe
        $kobolds = $this->tribe->getAliveKobolds();
        
        // Modify state
        foreach ($kobolds as $kobold) {
            if ($kobold->checkStat('vitality')) {
                // Success
            } else {
                // Fail - maybe injury
                $kobold->addInjury('wound', 'wound', 1);
            }
        }
        
        $this->story .= "\nThe hunters returned...";
        return $this->story;
    }
}
```

## Storage Structure

User saves are stored entirely in the SQLite database. Per-user directories in `data/users/` are reserved for:
- Modified sprites (if sprite transformation is implemented)
- Custom user content
- Temporary files

Format: `data/users/{userId}/{koboldId}/sprite/` for modified sprites

## Frontend Architecture

### Screens
- Auth Screen: Login/register
- Main Menu: List saves, new game
- Game Setup: Tribe generation and selection
- Game Screen: Main gameplay with events
- Config Screen: Enable/disable content
- Event Modal: Story display

### State Management
- `currentUser`: Logged-in user object
- `currentSave`: Current save metadata
- `currentTribe`: Current tribe with kobolds

### Communication
- Fetch API for all server communication
- JSON request/response
- Token in Authorization header

## Extensibility Points

### New Events
1. Create class extending `Event`
2. Register in `EventManager::registerEventClasses()`
3. No database changes needed

### New Injuries
1. Add injury type in events
2. Ensure category is in injury type map
3. Optional: add to `injuries_enabled` table

### New Items
1. Create items via API or events
2. Set stat modifications
3. Store in items table

### New Stats
1. Add to `Kobold::$statNames`
2. Ensure database has column (migration needed)
3. All stat systems auto-support new stat

### New Age Tiers
1. Modify age tier detection in `Kobold::getAgeCategory()`
2. Update sprite selection
3. May need new sprites in morphs
