<?php

require_once __DIR__ . '/../../src/Events/Event.php';
require_once __DIR__ . '/../../src/Utilities/GameHelper.php';

class ExplorationEvent extends Event
{
    public function execute()
    {
        $this->story = "The exploration party ventured forth into uncharted territory...\n\n";

        $available = $this->tribe->getAliveKobolds();

        if (empty($available)) {
            $this->story .= "But there were no kobolds to send exploring!";
            return;
        }

        // Exploration must be started with explicit participants (player-started)
        $participantIds = $this->getParticipants();
        if (empty($participantIds) || !is_array($participantIds)) {
            throw new \Exception('ExplorationEvent requires a participants array of kobold IDs.');
        }

        $explorers = [];
        foreach ($participantIds as $pid) {
            $k = $this->tribe->getKobold($pid);
            if ($k && !$k->isDead())
                $explorers[] = $k;
        }

        if (empty($explorers)) {
            throw new \Exception('No valid living kobolds found in participants list.');
        }

        $this->story .= "A group of " . count($explorers) . " intrepid explorers set out:\n";
        foreach ($explorers as $explorer) {
            $this->story .= "- " . $explorer->getName() . " (Intelligence: " . getStatLabel($explorer->getStat('intelligence')) . ")\n";
        }
        $this->story .= "\n";

        // Chance to find food (50% base)
        $foodFound = rand(1, 100) <= 50;
        if ($foodFound) {
            $baseFood = rand(5, 15);
            // Intelligence affects food discovery - smarter kobolds find more
            $avgIntelligence = array_sum(array_map(function ($k) {
                return $k->getStat('intelligence');
            }, $explorers)) / count($explorers);
            $foodBonus = intval($avgIntelligence / 20); // Max +5 food from intelligence
            $totalFood = $baseFood + $foodBonus;

            $this->tribe->addFood($totalFood);
            $this->story .= "Success! The explorers discovered edible plants and small game.\n";
            $this->story .= "The tribe gained " . $totalFood . " units of food.\n\n";
        } else {
            $this->story .= "The terrain was barren. No food was found.\n\n";
        }

        // Chance for injury (large chance for testing) - someone trips on loose stone
        $injuryChance = rand(1, 100) <= 70; // higher for testing
        if ($injuryChance && count($explorers) > 0) {
            // Vitality affects injury chance - higher vitality = less likely to be injured
            $avgVitality = array_sum(array_map(function ($k) {
                return $k->getStat('vitality');
            }, $explorers)) / count($explorers);
            $injuryProbability = (100 - $avgVitality) / 100;

            if (rand(1, 100) / 100 <= $injuryProbability) {
                // Select a random explorer to get injured
                $injuredKobold = $explorers[array_rand($explorers)];

                $this->story .= "Disaster! " . $injuredKobold->getName() . " tripped over a loose stone!\n";

                // Try to load a predefined injury (brokenLeg) from assets
                $inj = GameHelper::loadInjury('brokenLeg');
                if ($inj) {
                    $inj['kobold_id'] = $injuredKobold->getId();
                    $inj['id'] = uniqid('inj_');
                    $injuries = $injuredKobold->getInjuries();
                    $injuries[] = $inj;
                    $injuredKobold->setInjuries($injuries);

                    $this->story .= $injuredKobold->getName() . " suffered a " . ($inj['injury_type'] ?? 'broken leg') . " (severity: " . ($inj['severity'] ?? 1) . "/10).\n";
                } else {
                    // Fallback to simple injury
                    $newInjury = [
                        'id' => uniqid('inj_'),
                        'kobold_id' => $injuredKobold->getId(),
                        'injury_type' => 'broken_leg',
                        'category' => 'fracture',
                        'severity' => rand(3, 7),
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                    $injuries = $injuredKobold->getInjuries();
                    $injuries[] = $newInjury;
                    $injuredKobold->setInjuries($injuries);

                    $this->story .= $injuredKobold->getName() . " suffered a broken leg (severity: " . $newInjury['severity'] . "/10).\n";
                }
            }
        }

        // For testing: add a 'bone-setting' item to tribe storage so player can cure fractures
        $boneItem = GameHelper::loadItem('bone-setting');
        if ($boneItem) {
            $this->tribe->addToStorage($boneItem);
            $this->story .= "The explorers also salvaged a Bone-setting kit and brought it back to storage.\n";
        }

        $this->story .= "\nThe exploration party returned to the tribe with their findings.";

        return $this->story;
    }
}
