<?php

require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../../src/Database/Database.php';
require_once __DIR__ . '/../../src/Classes/User.php';
require_once __DIR__ . '/../../src/Classes/Tribe.php';
require_once __DIR__ . '/../../src/Classes/Kobold.php';
require_once __DIR__ . '/../../src/Classes/Injury.php';
require_once __DIR__ . '/../../src/System/SaveManager.php';

foreach (glob(__DIR__ . "/../../src/Events/*Event.php") as $file) {
    require_once $file;
}

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    if (strpos($apiPath, 'generation') !== false) {
        // Generate initial kobolds for new game
        try {
            $userId = $input['userId'] ?? null;
            if (!$userId) {
                throw new \Exception('User ID required');
            }

            $tribe = Tribe::create($userId, $input['saveName']);

            $kobolds = [];
            for ($i = 0; $i < 18; $i++) {
                $kobold = Kobold::generate($userId, $tribe->getSaveId(), rand(15, 45));
                $tribe->addKobold($kobold);

                $kobolds[] = [
                    'id' => $kobold->getId(),
                    'name' => $kobold->getAgeCategory() !== "egg" ? $kobold->getName() : "Egg",
                    'title' => $tribe->getTitleForKobold($kobold),
                    'ageCategory' => $kobold->getAgeCategory(),
                    'age' => $kobold->getAge(),
                    'stats' => [
                        'vitality' => $kobold->getStat('vitality'),
                        'intelligence' => $kobold->getStat('intelligence'),
                        'medicine' => $kobold->getStat('medicine'),
                        'crafting' => $kobold->getStat('crafting'),
                        'personality' => $kobold->getStat('personality'),
                        'will' => $kobold->getStat('will'),
                        'fighting' => $kobold->getStat('fighting')
                    ],
                    'fatigue' => $kobold->getFatigue(),
                    'fatigue_label' => $kobold->getFatigueLabel()
                ];
            }

            $tribe->save();

            echo json_encode([
                'success' => true,
                'save' => [
                    'id' => $tribe->getSaveId(),
                    'name' => $input['saveName']
                ],
                'kobolds' => $kobolds
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'cureInjury') !== false) {
        // Cure an injury using an item from a kobold's inventory
        try {
            $userId = $input['userId'] ?? null;
            $saveId = $input['saveId'] ?? null;
            $koboldId = $input['koboldId'] ?? null;
            $injuryId = $input['injuryId'] ?? null;
            $itemId = $input['itemId'] ?? null;

            if (!$userId || !$saveId || !$koboldId || !$injuryId || !$itemId) {
                throw new \Exception('userId, saveId, koboldId, injuryId and itemId are required');
            }

            $tribe = Tribe::load($userId, $saveId);

            // find kobold
            $target = null;
            foreach ($tribe->getKobolds(false) as $k) {
                if ($k->getId() === $koboldId) {
                    $target = $k;
                    break;
                }
            }

            if (!$target)
                throw new \Exception('Kobold not found');

            // find injury in kobold
            $injuries = $target->getInjuries() ?? [];
            $injury = null;
            foreach ($injuries as $inj) {
                if ($inj['id'] === $injuryId) {
                    $injury = $inj;
                    break;
                }
            }

            if (!$injury)
                throw new \Exception('Injury not found');

            // malnourished cannot be cured via item
            if (($injury['category'] ?? '') === 'malnourished') {
                throw new \Exception('Malnourishment is cured via feeding at month end');
            }

            // required medicine by category
            $required = Injury::getCureForCategory($injury['category'] ?? null);
            if (!$required)
                throw new \Exception('This injury cannot be cured with items');

            if ($required !== $itemId) {
                throw new \Exception('Provided item does not match required medicine');
            }

            $requiredStat = Injury::getStatRequiredToCure($injury['severity'] ?? null);
            $doctor = null;
            if ($requiredStat !== null) {
                $bestOther = null;
                $bestOtherMed = -1;
                foreach ($tribe->getKobolds(false) as $k) {
                    if ($k->getId() === $koboldId) {
                        continue;
                    }
                    $med = (int) ($k->getStat('medicine') ?? 0);
                    if ($med >= $requiredStat && $med > $bestOtherMed) {
                        $bestOther = $k;
                        $bestOtherMed = $med;
                    }
                }

                if ($bestOther) {
                    $doctor = $bestOther;
                } else {
                    $selfMed = (int) ($target->getStat('medicine') ?? 0);
                    if ($selfMed >= $requiredStat) {
                        $doctor = $target;
                    }
                }

                if (!$doctor) {
                    throw new \Exception('No kobold has sufficient medicine skill to treat this injury');
                }
            } else {
                $doctor = $target;
            }

            $itemName = $itemId;
            $itemSource = null;
            $consumeItem = function ($items) use ($itemId, &$itemName) {
                $found = false;
                $newItems = [];
                $picked = null;
                foreach ($items ?? [] as $it) {
                    $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
                    if ($iid === $itemId && !$found) {
                        $found = true;
                        $picked = $it;
                        // capture name if present
                        if (is_array($it) && isset($it['name']))
                            $itemName = $it['name'];
                        elseif (is_object($it) && method_exists($it, 'getName'))
                            $itemName = $it->getName();
                        continue;
                    }
                    $newItems[] = $it;
                }
                return [$found, $newItems, $picked];
            };

            // try consume from target first
            [$foundTarget, $newTargetItems, $pickedTarget] = $consumeItem($target->getItems() ?? []);
            if ($foundTarget) {
                $itemSource = 'target';
                $reflection = new ReflectionClass($target);
                if ($reflection->hasProperty('items')) {
                    $prop = $reflection->getProperty('items');
                    $prop->setValue($target, $newTargetItems);
                }
            } else if ($doctor && $doctor->getId() !== $target->getId()) {
                [$foundDoctor, $newDoctorItems, $pickedDoctor] = $consumeItem($doctor->getItems() ?? []);
                if ($foundDoctor) {
                    $itemSource = 'doctor';
                    $reflection = new ReflectionClass($doctor);
                    if ($reflection->hasProperty('items')) {
                        $prop = $reflection->getProperty('items');
                        $prop->setValue($doctor, $newDoctorItems);
                    }
                }
            }

            if (!$itemSource) {
                $storage = $tribe->getStorage() ?? [];
                [$foundStorage, $newStorage, $pickedStorage] = $consumeItem($storage);
                if ($foundStorage) {
                    $itemSource = 'storage';
                    $refT = new ReflectionClass($tribe);
                    if ($refT->hasProperty('storage')) {
                        $p = $refT->getProperty('storage');
                        $p->setValue($tribe, array_values($newStorage));
                    }
                }
            }

            if (!$itemSource) {
                throw new \Exception('No valid source has the required item');
            }

            // remove injury
            $target->removeInjury($injuryId);

            // save tribe
            $tribe->save();

            $koboldName = $target->getName();
            $injuryName = $injury['injury_type'] ?? ($injury['injuryType'] ?? 'injury');

            $doctorName = $doctor ? $doctor->getName() : $koboldName;
            $itemSourceText = 'from their own inventory';
            if ($itemSource === 'target') {
                if ($doctor && $doctor->getId() !== $target->getId()) {
                    $itemSourceText = "from {$koboldName}'s inventory";
                }
            } elseif ($itemSource === 'doctor') {
                $itemSourceText = "from {$doctorName}'s inventory";
            } elseif ($itemSource === 'storage') {
                $itemSourceText = 'from tribe storage';
            }
            if ($doctor && $doctor->getId() !== $target->getId()) {
                $story = "{$doctorName} treated {$koboldName}'s {$injuryName} using the {$itemName} {$itemSourceText}.";
            } else {
                $story = "{$doctorName} used the {$itemName} {$itemSourceText} to cure the {$injuryName}.";
            }

            echo json_encode(['success' => true, 'story' => $story]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    } elseif (strpos($apiPath, 'giveItem') !== false) {
        // Move item from tribe storage to kobold inventory and save
        try {
            $userId = $input['userId'] ?? null;
            $saveId = $input['saveId'] ?? null;
            $koboldId = $input['koboldId'] ?? null;
            $itemId = $input['itemId'] ?? null;

            if (!$userId || !$saveId || !$koboldId || !$itemId) {
                throw new \Exception('userId, saveId, koboldId and itemId are required');
            }

            $tribe = Tribe::load($userId, $saveId);

            // find item in storage
            $storage = $tribe->getStorage() ?? [];
            $found = null;
            $newStorage = [];
            foreach ($storage as $s) {
                $sid = is_array($s) ? ($s['id'] ?? null) : (is_object($s) && method_exists($s, 'getId') ? $s->getId() : null);
                if ($sid === $itemId && $found === null) {
                    $found = $s;
                    continue;
                }
                $newStorage[] = $s;
            }

            if ($found === null)
                throw new \Exception('Item not found in storage');

            // find kobold
            $target = null;
            foreach ($tribe->getKobolds(false) as $k) {
                if ($k->getId() === $koboldId) {
                    $target = $k;
                    break;
                }
            }
            if (!$target)
                throw new \Exception('Kobold not found');

            // add item to kobold
            if (method_exists($target, 'addItem')) {
                $target->addItem($found);
            } else {
                // fallback: set via reflection
                $ref = new ReflectionClass($target);
                if ($ref->hasProperty('items')) {
                    $prop = $ref->getProperty('items');
                    $items = $prop->getValue($target) ?? [];
                    $items[] = $found;
                    $prop->setValue($target, $items);
                }
            }

            // write back storage
            $refT = new ReflectionClass($tribe);
            if ($refT->hasProperty('storage')) {
                $p = $refT->getProperty('storage');
                $p->setValue($tribe, array_values($newStorage));
            }

            $tribe->save();

            $koboldName = $target->getName();
            $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
            $story = "{$itemName} was given to {$koboldName}.";

            echo json_encode(['success' => true, 'story' => $story]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    } elseif (strpos($apiPath, 'returnItem') !== false) {
        // Move item from kobold inventory back to tribe storage and save
        try {
            $userId = $input['userId'] ?? null;
            $saveId = $input['saveId'] ?? null;
            $koboldId = $input['koboldId'] ?? null;
            $itemId = $input['itemId'] ?? null;

            if (!$userId || !$saveId || !$koboldId || !$itemId) {
                throw new \Exception('userId, saveId, koboldId and itemId are required');
            }

            $tribe = Tribe::load($userId, $saveId);

            // find kobold
            $target = null;
            foreach ($tribe->getKobolds(false) as $k) {
                if ($k->getId() === $koboldId) {
                    $target = $k;
                    break;
                }
            }
            if (!$target)
                throw new \Exception('Kobold not found');

            // find item in kobold inventory
            $found = null;
            $newItems = [];
            foreach ($target->getItems() ?? [] as $it) {
                $iid = is_array($it) ? ($it['id'] ?? null) : (is_object($it) && method_exists($it, 'getId') ? $it->getId() : null);
                if ($iid === $itemId && $found === null) {
                    $found = $it;
                    continue;
                }
                $newItems[] = $it;
            }
            if ($found === null)
                throw new \Exception('Item not found on kobold');

            // set kobold items
            if (method_exists($target, 'removeItem')) {
                $target->removeItem($itemId);
            } else {
                $ref = new ReflectionClass($target);
                if ($ref->hasProperty('items')) {
                    $p = $ref->getProperty('items');
                    $p->setValue($target, $newItems);
                }
            }

            // add to tribe storage
            $storage = $tribe->getStorage() ?? [];
            $storage[] = $found;
            $refT = new ReflectionClass($tribe);
            if ($refT->hasProperty('storage')) {
                $p = $refT->getProperty('storage');
                $p->setValue($tribe, $storage);
            }

            $tribe->save();

            $koboldName = $target->getName();
            $itemName = is_array($found) ? ($found['name'] ?? $itemId) : (is_object($found) && method_exists($found, 'getName') ? $found->getName() : $itemId);
            $story = "{$koboldName} returned the {$itemName} to storage.";

            echo json_encode(['success' => true, 'story' => $story]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => $e->getMessage()]);
        }
    } elseif (strpos($apiPath, 'save') !== false && strpos($apiPath, 'endMonth') === false) {
        // Save tribe setup
        try {
            $userId = $input['userId'] ?? null;
            $saveId = $input['saveId'] ?? null;
            $environmentId = $input['environmentId'] ?? null;

            if (!$userId || !$saveId) {
                throw new \Exception('User ID and Save ID required');
            }

            $tribe = Tribe::load($userId, $saveId);

            if ($environmentId !== null) {
                $tribe->setEnvironmentId($environmentId);
            }

            $leaderI = intval($input['leaderId']) ?? 0;

            $keys = array_keys($tribe->kobolds);
            $i = $keys[$leaderI];
            $tribe->kobolds[$i]->setName($input['leaderName']);
            $tribe->kobolds[$i]->setLeader();

            for ($i = 0; $i < count($input['memberIndices']); $i++) {
                $input['memberIndices'][$i] = array_keys($tribe->kobolds)[$input['memberIndices'][$i]];
            }

            $tribe->kobolds = array_filter($tribe->kobolds, function ($kobold, $index) use ($input) {
                return in_array($index, $input['memberIndices']);
            }, ARRAY_FILTER_USE_BOTH);

            $tribe->kobolds = array_values($tribe->kobolds);
            $tribe->save();

            echo json_encode([
                'success' => true,
                'tribe' => []
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'event') !== false) {
        // Execute an event
        try {
            $userId = $input['userId'] ?? null;
            $saveId = $input['saveId'] ?? null;

            if (!$userId || !$saveId) {
                throw new \Exception('User ID and Save ID required');
            }

            $tribe = Tribe::load($userId, $saveId);

            // Execute event and get story. Allow passing participant kobold IDs.
            $className = $input['eventType'] . "Event";
            if (!class_exists($className))
                throw new \Exception('Unknown event type');
            $event = new $className($tribe);

            if (method_exists($event, 'isAvailable') && !$event->isAvailable()) {
                throw new \Exception('That event is not available right now.');
            }

            // Player-started events MUST provide participants (array of kobold IDs)
            $participants = $input['participants'] ?? null;
            if (empty($participants) || !is_array($participants)) {
                throw new \Exception('You must provide a non-empty participants array of kobold IDs when starting an event.');
            }

            // validate count against event limits
            $min = method_exists($event, 'getMinParticipants') ? $event->getMinParticipants() : 1;
            $max = method_exists($event, 'getMaxParticipants') ? $event->getMaxParticipants() : 3;
            $count = count($participants);
            if ($count < $min || $count > $max) {
                throw new \Exception("Participants must be between {$min} and {$max}");
            }

            $cost = $event->getCost();
            $participantKobolds = [];
            $ineligible = [];
            foreach ($participants as $pid) {
                $kobold = $tribe->getKobold($pid);
                if (!$kobold || $kobold->isDead()) {
                    throw new \Exception('One or more selected kobolds are unavailable.');
                }

                if (($kobold->getFatigue() + $cost) > $kobold->getStat('vitality')) {
                    $ineligible[] = $kobold->getName();
                } else {
                    $participantKobolds[] = $kobold;
                }
            }

            if (!empty($ineligible)) {
                $names = implode(', ', $ineligible);
                throw new \Exception("These kobolds are too fatigued for this event: {$names}");
            }

            $event->setParticipants($participants);

            $event?->execute();
            $story = $event?->getStory() ?? 'No event occurred.';

            foreach ($participantKobolds as $kobold) {
                $kobold->addFatigue($cost);
                if ($kobold->isDead()) {
                    $story = $story . "\n" . $kobold->getName() . " has died.";
                }
            }

            $tribe->save();

            echo json_encode([
                'success' => true,
                'story' => $story
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'endMonth') !== false) {
        // End the current month
        try {
            $userId = $input['userId'] ?? null;
            $saveId = $input['saveId'] ?? null;

            if (!$userId || !$saveId) {
                throw new \Exception('User ID and Save ID required');
            }

            $tribe = Tribe::load($userId, $saveId);
            $foodStory = $tribe->endMonth();

            echo json_encode([
                'success' => true,
                'save' => [
                    'id' => $tribe->getSaveId(),
                    'current_month' => $tribe->getCurrentMonth(),
                    'current_season' => $tribe->getCurrentSeason(),
                    'food_count' => $tribe->getFoodCount()
                ],
                'monthStory' => $foodStory
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }
} elseif ($method === 'GET') {
    $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    if (strpos($apiPath, 'sprite') !== false) {
        // Serve a kobold sprite image
        try {
            $userId = $_GET['userId'] ?? null;
            $koboldId = $_GET['koboldId'] ?? null;

            if (!$userId || !$koboldId) {
                throw new \Exception('User ID and Kobold ID required');
            }

            $saveManager = new SaveManager();
            $ageSprite = $_GET['age'] ?? 'adult';
            $spritePath = $saveManager->getKoboldSpritePath($userId, $koboldId, $ageSprite);
            $spriteFile = $spritePath;

            if (!file_exists($spriteFile)) {
                throw new \Exception('Sprite not found');
            }

            // Serve the sprite image
            header('Content-Type: image/png');
            header('Cache-Control: public, max-age=3600');
            readfile($spriteFile);
            exit;
        } catch (\Exception $e) {
            http_response_code(404);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'environments') !== false) {
        // List available environments and metadata
        try {
            $basePath = __DIR__ . '/../../assets/environments';
            if (!is_dir($basePath)) {
                throw new \Exception('Environments directory not found');
            }

            $envs = [];
            $dirs = array_filter(scandir($basePath), function ($dir) use ($basePath) {
                return $dir[0] !== '.' && is_dir($basePath . '/' . $dir);
            });

            $seasons = ['spring', 'summer', 'autumn', 'winter'];

            foreach ($dirs as $dir) {
                $metaFile = $basePath . '/' . $dir . '/metadata.json';
                $meta = [];
                if (file_exists($metaFile)) {
                    $meta = json_decode(file_get_contents($metaFile), true) ?? [];
                }

                $images = [];
                foreach ($seasons as $season) {
                    $imgPath = $basePath . '/' . $dir . '/' . $season . '.png';
                    if (file_exists($imgPath)) {
                        $images[] = 'assets/environments/' . $dir . '/' . $season . '.png';
                    }
                }

                if (empty($images)) {
                    foreach (glob($basePath . '/' . $dir . '/*.png') as $img) {
                        $images[] = 'assets/environments/' . $dir . '/' . basename($img);
                    }
                }

                $envs[] = [
                    'id' => $dir,
                    'name' => $meta['name'] ?? $dir,
                    'description' => $meta['description'] ?? '',
                    'koboldLocations' => $meta['koboldLocations'] ?? [],
                    'images' => $images
                ];
            }

            echo json_encode([
                'success' => true,
                'environments' => $envs
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'list') !== false) {
        // List saves for user
        try {
            $userId = $_SESSION['user_email'] ?? null;

            if (!$userId) {
                throw new \Exception('Not authenticated');
            }

            $user = new User($userId, '');
            $saves = $user->getSaves();

            echo json_encode([
                'success' => true,
                'saves' => $saves
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'load') !== false) {
        // Load a specific game save
        try {
            $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
            $saveId = $_GET['saveId'] ?? null;

            if (!$userId || !$saveId) {
                throw new \Exception('User ID and Save ID required');
            }

            $tribe = Tribe::load($userId, $saveId);

            // Get kobolds with full stats, items and injuries
            $kobolds = getKobolds($tribe, false);
            $rivals = getKobolds($tribe, true);

            // Get storage items
            $storage = $tribe->getStorage();

            echo json_encode([
                'success' => true,
                'save' => [
                    'id' => $tribe->getSaveId(),
                    'name' => $tribe->getName(),
                    'current_month' => $tribe->getCurrentMonth(),
                    'current_season' => $tribe->getCurrentSeason(),
                    'environment_id' => $tribe->getEnvironmentId(),
                    'food_count' => $tribe->getFoodCount(),
                    'food_time_remaining' => $tribe->foodTimeStr($tribe->getFoodCount()),
                    'created_at' => $tribe->getCreatedAt(),
                    'last_played' => $tribe->getLastPlayed(),
                    'rivals' => $rivals
                ],
                'tribe' => [
                    'kobolds' => $kobolds,
                    'storage' => $storage
                ]
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'events') !== false) {
        // List available events and their costs
        try {
            $userId = $_GET['userId'] ?? $_SESSION['user_id'] ?? null;
            $saveId = $_GET['saveId'] ?? null;

            if (!$userId || !$saveId) {
                throw new \Exception('User ID and Save ID required');
            }

            $tribe = Tribe::load($userId, $saveId);

            $events = [];
            foreach (get_declared_classes() as $className) {
                if (!is_subclass_of($className, 'Event') || $className === 'MonthEndEvent') {
                    continue;
                }

                $event = new $className($tribe);

                if ($event->isEndOfMonth())
                    continue;

                $type = preg_replace('/Event$/', '', $className);

                $events[] = [
                    'type' => $type,
                    'name' => $type,
                    'cost' => $event->getCost(),
                    'available' => $event->isAvailable(),
                    'min_participants' => $event->getMinParticipants(),
                    'max_participants' => $event->getMaxParticipants(),
                    'min_age' => $event->getMinAge(),
                ];
            }

            echo json_encode([
                'success' => true,
                'events' => $events
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }
}

function getKobolds($tribe, $getRivals): array
{
    $kobolds = [];
    foreach ($tribe->getKobolds($getRivals === true) as $kobold) {
        $kInjuries = $kobold->getInjuries() ?? [];
        // enrich injuries with required medicine mapping
        foreach ($kInjuries as &$inj) {
            $req = null;
            if (class_exists('Injury')) {
                $req = Injury::getCureForCategory($inj['category'] ?? null);
            }
            if ($req !== null) {
                $inj['required_medicine'] = $req;

                $category = $inj['category'] ?? null;
                if ($category !== 'malnourished' && $category !== 'old-age') {
                    $statReq = Injury::getStatRequiredToCure($inj['severity'] ?? null);
                    if ($statReq !== null) {
                        $inj['stat_required_to_cure'] = $statReq;
                    }
                }
            }
        }

        $kobolds[] = [
            'id' => $kobold->getId(),
            'name' => $kobold->getAgeCategory() !== "egg" ? $kobold->getName() : "Egg",
            'title' => $tribe->getTitleForKobold($kobold),
            'age' => $kobold->getAge(),
            'ageCategory' => $kobold->getAgeCategory(),
            'stats' => [
                'vitality' => $kobold->getStat('vitality'),
                'intelligence' => $kobold->getStat('intelligence'),
                'medicine' => $kobold->getStat('medicine'),
                'crafting' => $kobold->getStat('crafting'),
                'personality' => $kobold->getStat('personality'),
                'will' => $kobold->getStat('will'),
                'fighting' => $kobold->getStat('fighting')
            ],
            'fatigue' => $kobold->getFatigue(),
            'fatigue_label' => $kobold->getFatigueLabel(),
            'items' => $kobold->getItems() ?? [],
            'injuries' => $kInjuries,
            'is_leader' => $kobold->isLeader(),
            'male' => $kobold->getMale(),
            'likes' => isset($kobold->dataStore) && $kobold->dataStore instanceof stdClass
                && isset($kobold->dataStore->likes) && is_array($kobold->dataStore->likes)
                ? $kobold->dataStore->likes
                : []
        ];
    }

    return $kobolds;
}