# Database Refactoring Complete: File-Based Storage

## Overview
Successfully refactored TribeGen from a complex database-heavy architecture to a hybrid approach:
- **Database (SQLite)**: User accounts only (users table)
- **File System (JSON)**: All game data in `/data/saves/{userId}/{saveId}/` directory structure

## Architecture Changes

### Storage Structure
```
/data/saves/
├── {userId}/
│   ├── 1/                    # Save 1
│   │   ├── save.json        # Tribe metadata (name, month, season, food_count, dates)
│   │   ├── kobolds.json     # Array of all kobolds with stats/injuries/items
│   │   ├── items.json       # Tribe storage items
│   │   └── npcs.json        # NPC list
│   ├── 2/                    # Save 2
│   └── kobolds/
│       ├── {koboldId}/
│       │   └── sprites/      # Modified sprite files for this kobold
```

### Refactored Classes

#### SaveManager (NEW)
- **Purpose**: Central abstraction for all file I/O operations
- **Key Methods**:
  - `getUserSavesPath($userId)` - creates and returns user save directory
  - `getSavePath($userId, $saveId)` - creates and returns specific save directory
  - `getKoboldSpritePath($userId, $koboldId)` - creates and returns sprite storage path
  - `saveJson($filePath, $data)` - writes JSON with error handling and pretty-printing
  - `loadJson($filePath)` - reads JSON with null handling on missing files
  - `listUserSaves($userId)` - scans directory, loads save.json files, returns sorted by last_played
  - `generateSaveId($userId)` - generates next numeric save ID by scanning directory
  - `deleteSave($userId, $saveId)` - recursive directory deletion
- **Location**: `src/System/SaveManager.php` (115 lines)

#### Tribe (REFACTORED)
- **Previous**: Used database for all save data persistence
- **Now**: 
  - Loads/saves all data from JSON files via SaveManager
  - `create()` - creates new save with SaveManager ID generation
  - `load()` - loads from JSON files (requires userId and saveId now)
  - `save()` - writes save.json (metadata), kobolds.json (array), items.json
  - Constructor now takes `$userId` and `$saveId` parameters
  - `loadFromFile()` - reads save.json on initialization
  - `loadKobolds()` - reads kobolds.json and reconstructs kobold objects
  - `loadStorage()` - reads items.json
- **Location**: `src/Classes/Tribe.php`

#### Kobold (REFACTORED)
- **Previous**: Used database INSERT/UPDATE/SELECT for persistence
- **Now**:
  - Stored as part of Tribe's kobolds.json array
  - Constructor requires `$userId` parameter (new)
  - Uses `uniqid('kob_')` for unique ID generation instead of database auto-increment
  - New methods: `fromArray()` and `toArray()` for JSON serialization
  - `save()` is now a no-op (saves via Tribe.save())
  - Injuries now use `uniqid('inj_')` for IDs instead of database PKs
- **Location**: `src/Classes/Kobold.php`

#### Item (REFACTORED)
- **Previous**: Used database for stat modifications lookup
- **Now**:
  - Constructor includes `$statModifications` parameter
  - New methods: `fromArray()` and `toArray()` for JSON serialization
  - Removed `loadModifications()` - all data passed in constructor
- **Location**: `src/Classes/Item.php`

#### NPC (REFACTORED)
- **Previous**: Used database INSERT/UPDATE for persistence
- **Now**:
  - Creates with `uniqid('npc_')` for IDs
  - New methods: `fromArray()` and `toArray()` for JSON serialization
  - `save()` is now a no-op (saves via Tribe.save())
- **Location**: `src/Classes/NPC.php`

#### User (REFACTORED)
- **No Change to Auth**: Database still used for register/login (password hashing)
- **Changed getSaves()**: Now uses `SaveManager.listUserSaves()` instead of SQL query
- **Location**: `src/Classes/User.php`

#### Database (SIMPLIFIED)
- **Previous**: 13 tables (saves, kobolds, injuries, items, kobold_items, item_modifications, events_enabled, injuries_enabled, npcs, etc.)
- **Now**: 1 table only - `users` (id, email, password_hash, created_at)
- **Impact**: Removed all game-related table creation from `initializeTables()`
- **Location**: `src/Database/Database.php`

### API Changes

#### game.php (UPDATED)
- **Tribe::create()**: Now requires `$userId` parameter
- **Tribe::load()**: Now requires both `$userId` and `$saveId` parameters
- **Kobold::generate()**: Now requires `$userId` and `$saveId` parameters
- **listUserSaves**: Uses `SaveManager.listUserSaves()` instead of database query
- **Generation endpoint**: Creates initial 20 kobolds and saves via Tribe.save()
- **Load endpoint**: Retrieves from JSON files and constructs objects
- **Location**: `src/api/game.php`

### File Serialization Format

#### save.json (Tribe Metadata)
```json
{
  "name": "My Tribe",
  "current_month": 0,
  "current_season": "spring",
  "food_count": 100,
  "created_at": "2024-01-15 10:30:45",
  "last_played": "2024-01-15 11:45:30"
}
```

#### kobolds.json (All Kobolds)
```json
[
  {
    "id": "kob_12345abc",
    "name": "Grok",
    "age": 15,
    "stats": {
      "vitality": 75,
      "intelligence": 60,
      ...
    },
    "sprite_morph": "default",
    "is_leader": true,
    "is_alive": true,
    "is_expelled": false,
    "injuries": [
      {
        "id": "inj_xyz",
        "category": "wound",
        "injury_type": "cut_arm",
        "severity": 2
      }
    ],
    "items": [],
    "father_id": null,
    "mother_id": null
  }
]
```

#### items.json (Tribe Storage)
```json
[
  {
    "id": "itm_abc123",
    "save_id": "1",
    "name": "Iron Axe",
    "description": "A sturdy iron axe",
    "item_type": "weapon",
    "stat_modifications": {
      "crafting": 5
    }
  }
]
```

## Key Improvements

1. **Portability**: All game saves are JSON files, easily portable and versionable with git
2. **Inspectability**: Can manually examine and edit save files
3. **Reduced Database Load**: Only user authentication uses database
4. **Simpler Queries**: No complex joins or foreign key constraints
5. **Faster Iteration**: No need for migrations for game data changes
6. **Backup Friendly**: Can zip/copy individual save directories

## Migration Path

If existing saves exist in database:
1. Query the old tables
2. Construct Tribe/Kobold/Item/NPC objects
3. Save via Tribe.save() to create JSON files
4. Can then safely remove database tables

## Testing Considerations

- Create new save: Tests Tribe.create() and JSON file creation
- Load save: Tests Tribe.load() and JSON parsing
- List saves: Tests SaveManager.listUserSaves() sorting and filtering
- End month: Tests Tribe.endMonth() and file persistence
- Food system: Already integrated with JSON storage

## Backwards Compatibility

All game classes maintain the same public API:
- `Tribe::create()`, `Tribe::load()` still exist
- `Kobold.save()`, `addInjury()`, `removeInjury()` still work
- No changes to gameplay logic, only persistence layer

The only API change is method signatures requiring `userId` parameter for Tribe/Kobold operations.
