<?php

require_once __DIR__ . '/../../src/Events/MonthEndEvent.php';
require_once __DIR__ . '/../../src/Classes/Kobold.php';

class RivalEncounterEvent extends MonthEndEvent
{
    public function getMinAge()
    {
        return 15;
    }

    public function getMinParticipants()
    {
        return 1;
    }

    public function getMaxParticipants()
    {
        return 1;
    }

    public function getCost()
    {
        return 55;
    }

    public function isAvailable()
    {
        return true;
    }

    public function execute()
    {
        $this->story = '';

        $eligible = array_filter($this->tribe->getAliveKobolds(), fn($k) => $k->getAge() >= $this->getMinAge());
        $eligible = array_values($eligible);

        if (empty($eligible)) {
            return;
        }

        $kobold = $eligible[array_rand($eligible)];

        // Initialize rivals if not present
        if (!isset($this->tribe->rivals)) {
            $this->tribe->rivals = [];
        }

        $rivals = $this->tribe->rivals;

        // Generate or pick a rival
        $rival = null;

        if (count($rivals) < 10 && rand(1, 100) <= 40) {
            // Generate a new rival
            $rivalNames = ['Gruk', 'Zag', 'Mog', 'Drog', 'Bik', 'Kra', 'Nik', 'Tug', 'Vox', 'Warg'];
            $rivalName = $rivalNames[array_rand($rivalNames)];
            $rival = Kobold::generate($this->tribe->getUserId(), $this->tribe->getSaveId(), rand(13, 50), true);
            $this->tribe->rivals[] = $this->tribe->addKobold($rival, true);
        } elseif (!empty($rivals)) {
            // Pick an existing rival
            $rival = $rivals[array_rand($rivals)];
        }

        // If no rival exists, return
        if (!$rival) {
            return;
        }

        $koboldName = $kobold->getName();
        $rivalName = $rival->getName();

        // Check personality (kobold's perspective toward the rival)
        $personalityCheck = $kobold->checkStat('personality');

        $injuryTypes = ['smallCut', 'brokenLeg'];

        if ($personalityCheck) {
            // Positive encounter
            // Initialize kobold's likes if needed
            if (!isset($kobold->dataStore)) {
                $kobold->dataStore = new stdClass();
            }
            if (!isset($kobold->dataStore->likes)) {
                $kobold->dataStore->likes = [];
            }

            // Like the rival
            $currentLike = $kobold->dataStore->likes[$rival->getId()] ?? 0;
            $kobold->dataStore->likes[$rival->getId()] = $currentLike + 3;

            $positiveVariations = [
                "{$koboldName} encountered {$rivalName} and the two exchanged pleasantries. Relations improved slightly.",
                "When {$koboldName} met {$rivalName}, the encounter was surprisingly cordial.",
                "{$koboldName} and {$rivalName} ran into each other and found common ground.",
                "A chance meeting between {$koboldName} and {$rivalName} resulted in friendly conversation.",
                "{$koboldName} discovered that {$rivalName} might not be such a bad sort after all.",
            ];

            // Chance of receiving a gift
            if (rand(1, 100) <= 40) {
                $gifts = ['bone-setting', 'healing-herbs', 'book'];
                $giftName = $gifts[array_rand($gifts)];

                $giftVariations = [
                    $positiveVariations[array_rand($positiveVariations)] . " {$rivalName} even gifted {$koboldName} with a {$giftName}.",
                    $positiveVariations[array_rand($positiveVariations)] . " The encounter ended with {$rivalName} generously offering {$koboldName} a {$giftName}.",
                ];

                $this->story = $giftVariations[array_rand($giftVariations)];

                // Try to add gift to storage (if item loading available)
                if (class_exists('GameHelper')) {
                    $itemData = GameHelper::loadItem($giftName);
                    if ($itemData) {
                        $this->tribe->addToStorage($itemData);
                    }
                }
            } else {
                $this->story = $positiveVariations[array_rand($positiveVariations)];
            }
        } else {
            // Negative encounter - they fight
            $negativeVariations = [
                "{$koboldName} and {$rivalName} clashed bitterly when they met.",
                "An encounter between {$koboldName} and {$rivalName} quickly escalated into violence.",
                "{$koboldName} and {$rivalName} came to blows, leaving both wounded.",
                "When {$koboldName} crossed paths with {$rivalName}, tempers flared into a fight.",
                "{$koboldName} and {$rivalName} settled their differences through combat.",
            ];

            // Randomly injure the kobold
            if (rand(1, 100) <= 70) {
                $injury = $injuryTypes[array_rand($injuryTypes)];
                $kobold->addInjury($injury);

                $injuredVariations = [
                    $negativeVariations[array_rand($negativeVariations)] . " {$koboldName} came away with an injury.",
                    $negativeVariations[array_rand($negativeVariations)] . " {$koboldName} was hurt in the confrontation.",
                ];

                $this->story = $injuredVariations[array_rand($injuredVariations)];
            } else {
                $this->story = $negativeVariations[array_rand($negativeVariations)];
            }
        }

        $kobold->save();
    }
}
