<?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",
                    '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(true) 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');
            }

            // check kobold has the item
            $has = false;
            $itemName = $itemId;
            $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 && !$has) {
                    $has = true;
                    // 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();
                    // consume (skip adding to newItems)
                    continue;
                }
                $newItems[] = $it;
            }

            if (!$has)
                throw new \Exception('Kobold does not have the required item');

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

            // set kobold items to newItems (consumed)
            $reflection = new ReflectionClass($target);
            if ($reflection->hasProperty('items')) {
                $prop = $reflection->getProperty('items');
                $prop->setValue($target, $newItems);
            }

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

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

            $story = "{$koboldName} used the {$itemName} to cure their {$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(true) 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(true) 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 = [];
            foreach ($tribe->getKobolds() 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);
                    }
                    $inj['required_medicine'] = $req;
                }

                $kobolds[] = [
                    'id' => $kobold->getId(),
                    'name' => $kobold->getAgeCategory() !== "egg" ? $kobold->getName() : "Egg",
                    '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()
                ];
            }

            // 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()
                ],
                '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')) {
                    continue;
                }

                $event = new $className($tribe);
                $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()
            ]);
        }
    }
}

