# TribeGen: File-Based Architecture - Complete Mapping

## Architecture Overview

### Hybrid Storage Model
- **SQLite Database**: User authentication only
- **JSON Files**: All game saves and state
- **No Relationships**: All data is self-contained within save directories

---

## Directory Structure

```
tribegen/
├── src/
│   ├── api/
│   │   ├── auth.php              # Authentication endpoints (unchanged)
│   │   └── game.php              # Game endpoints (REFACTORED)
│   ├── Classes/
│   │   ├── User.php              # Auth + getSaves() (REFACTORED)
│   │   ├── Tribe.php             # Tribe state (REFACTORED to use SaveManager)
│   │   ├── Kobold.php            # Individual kobold (REFACTORED)
│   │   ├── Item.php              # Items (REFACTORED)
│   │   ├── NPC.php               # NPCs (REFACTORED)
│   │   ├── Injury.php            # Injury data (unchanged)
│   │   └── Events/
│   │       ├── Event.php         # Base event class (unchanged)
│   │       ├── HuntingEvent.php  # Hunting event (unchanged)
│   │       ├── ExplorationEvent.php
│   │       └── FarmingEvent.php
│   ├── Database/
│   │   └── Database.php          # Connection manager (SIMPLIFIED)
│   ├── System/
│   │   └── SaveManager.php       # File I/O abstraction (NEW)
│   └── Utilities/
│       ├── GameHelper.php        # Game helpers (unchanged)
│       └── EventManager.php      # Event orchestration (unchanged)
├── data/
│   └── saves/                    # All game saves directory
│       └── {userId}/
│           ├── 1/                # Save file 1
│           │   ├── save.json
│           │   ├── kobolds.json
│           │   ├── items.json
│           │   └── npcs.json
│           ├── 2/                # Save file 2
│           └── kobolds/
│               └── {koboldId}/sprites/  # Modified sprites
├── public/
│   ├── index.php                 # Router (minimal changes)
│   ├── index.html                # SPA (unchanged)
│   ├── js/
│   │   └── game.js               # Client logic (unchanged)
│   └── css/
│       └── style.css             # Styles (unchanged)
└── vendor/                       # Composer dependencies
```

---

## Class Signatures (Before → After)

### Tribe

**Before:**
```php
new Tribe($saveId)
Tribe::create($userId, $saveName)
Tribe::load($saveId)
$tribe->save()  // Used database
```

**After:**
```php
new Tribe($userId, $saveId, $name)
Tribe::create($userId, $saveName)  // Auto-generates saveId via SaveManager
Tribe::load($userId, $saveId)      // Requires userId
$tribe->save()  // Saves to JSON files
```

### Kobold

**Before:**
```php
new Kobold($id, $saveId, $name, $age, $spriteMorph)
Kobold::generate($saveId, $age)
$kobold->save()  // Database INSERT/UPDATE
$kobold->addInjury($type, $category, $severity)  // Database INSERT
```

**After:**
```php
new Kobold($id, $userId, $saveId, $name, $age, $spriteMorph)
Kobold::generate($userId, $saveId, $age)
$kobold->save()  // No-op (saved via Tribe)
$kobold->fromArray($data)  // Deserialize from JSON
$kobold->toArray()  // Serialize to JSON
$kobold->addInjury()  // Uses uniqid() instead of database
```

### Item

**Before:**
```php
new Item($id, $saveId, $name, $description, $itemType)
// Loaded modifications from database via constructor
```

**After:**
```php
new Item($id, $saveId, $name, $description, $itemType, $statModifications)
Item::fromArray($data)  // Create from JSON
$item->toArray()  // Serialize to JSON
```

### NPC

**Before:**
```php
NPC::create($saveId, $name, $npcType, $isRival)  // Database INSERT
NPC::load($id)  // Database SELECT
$npc->save()  // Database UPDATE
```

**After:**
```php
NPC::create($saveId, $name, $npcType, $isRival)  // Generates uniqid
NPC::fromArray($data)  // Create from JSON
$npc->toArray()  // Serialize to JSON
$npc->save()  // No-op (saved via Tribe)
```

### User

**Before & After:**
```php
User::register($email, $password)  // Still uses database
User::login($email, $password)     // Still uses database
$user->getSaves()  // WAS: SELECT from saves table
                   // NOW: SaveManager.listUserSaves()
```

---

## SaveManager API

```php
class SaveManager {
    // Directory Management
    public function getUserSavesPath($userId)           // Create/return /data/saves/{userId}/
    public function getSavePath($userId, $saveId)       // Create/return /data/saves/{userId}/{saveId}/
    public function getKoboldSpritePath($userId, $koboldId)  // Create/return sprites dir
    
    // JSON Persistence
    public function saveJson($filePath, $data)          // Write with error handling
    public function loadJson($filePath)                 // Read with error handling
    
    // Save Management
    public function listUserSaves($userId)              // Return array of saves, sorted
    public function generateSaveId($userId)             // Auto-increment numeric ID
    public function deleteSave($userId, $saveId)        // Recursive delete
}
```

---

## Database Changes

### Before (13 tables)
```sql
users
saves
kobolds
injuries
items
kobold_items
item_modifications
events_enabled
injuries_enabled
npcs
-- (plus other tables)
```

### After (1 table)
```sql
users (id, email, password_hash, created_at)
```

All other data is stored in JSON files under `/data/saves/`.

---

## API Endpoint Changes

### POST /api/game/generation
**Before:**
```json
{
  "userId": 1,
  "saveName": "My First Tribe"
}
// Returned: saveId from database
```

**After:**
```json
{
  "userId": 1,
  "saveName": "My First Tribe"
}
// Returns: saveId from SaveManager.generateSaveId()
// Creates: /data/saves/1/1/save.json with tribe metadata
//          /data/saves/1/1/kobolds.json with 20 kobolds
```

### GET /api/game/list
**Before:**
```sql
SELECT * FROM saves WHERE user_id = ? ORDER BY last_played DESC
```

**After:**
```php
SaveManager.listUserSaves($userId)
// Scans /data/saves/{userId}/ directory
// Loads save.json from each subdirectory
// Returns sorted array
```

### GET /api/game/load
**Before:**
```sql
SELECT * FROM saves WHERE id = ?
SELECT * FROM kobolds WHERE save_id = ?
-- Multiple queries with JOINs
```

**After:**
```php
Tribe::load($userId, $saveId)
// Reads /data/saves/{userId}/{saveId}/save.json
// Reads /data/saves/{userId}/{saveId}/kobolds.json
// Reconstructs objects from JSON
```

---

## Data Migration (Optional)

If you have existing saves in the old database:

```php
// Pseudo-code for migration
$saveManager = new SaveManager();

// Get all old saves from database
$stmt = $pdo->query("SELECT * FROM saves");
foreach ($stmt->fetchAll() as $saveRow) {
    // Load tribe from old database
    $tribe = Tribe::load($saveRow['id']);
    
    // Tribe now reads from database in constructor
    // Save to JSON via SaveManager
    $tribe->save();
    
    // Now JSON files exist at /data/saves/{userId}/{saveId}/
}

// Can then safely drop old tables
$pdo->exec("DROP TABLE IF EXISTS saves, kobolds, injuries, ...");
```

---

## Key Design Decisions

1. **SaveManager Abstraction**: All file I/O goes through one class for consistency
2. **Numeric Save IDs**: Simple incrementing IDs (1, 2, 3...) per user
3. **Array Serialization**: Kobolds/Items/NPCs stored as JSON arrays, not individual files
4. **No Foreign Keys**: JSON doesn't enforce relationships; parent_id/mother_id are simple strings
5. **Uniqid for PKs**: No auto-increment in JSON; use `uniqid('prefix_')` for unique IDs
6. **Single User Table**: Database only needed for authentication; all else is file-based

---

## Performance Implications

### Advantages
- No network latency for game operations (local file I/O)
- No query planning overhead
- Easier caching (just load JSON into memory)
- Faster writes (JSON serialization is fast)

### Considerations
- Loading full tribe into memory (not streaming)
- No partial reads (always load entire save)
- No indexing (linear scans for save lists)
- File locking for concurrent access (minor issue with single-player)

### Optimization Opportunities (Future)
- Cache loaded tribues in-memory with TTL
- Lazy-load kobolds on demand
- Save only changed objects instead of full serialization
- Use MessagePack instead of JSON for binary efficiency

---

## Backwards Compatibility

✅ Public API preserved (with signature updates):
- `Tribe::create()`, `Tribe::load()` exist
- `Kobold.save()` exists (now no-op)
- All game logic unchanged

❌ Breaking changes:
- `Tribe::load()` now requires `$userId` parameter
- `Kobold::generate()` now requires `$userId` parameter
- Database queries replaced with SaveManager calls

---

## Testing Checklist

- [ ] Create new save → saves to /data/saves/{userId}/{saveId}/
- [ ] Load save → reads from JSON files
- [ ] List saves → returns correct order by last_played
- [ ] End month → updates save.json with new month/season
- [ ] Food consumption → persists food_count in save.json
- [ ] Delete save → removes /data/saves/{userId}/{saveId}/ directory
- [ ] Multiple saves per user → no conflicts with numeric IDs
- [ ] Offline editing → can modify JSON and load in game

---

## Future Enhancements

1. **Cloud Sync**: Upload saves to server, sync across devices
2. **Save Versioning**: Keep multiple versions of saves
3. **Shared Saves**: Allow cooperative play (merge saves)
4. **Analytics**: Track which saves are most played
5. **Export Formats**: Convert to CSV, Excel, or other formats
