<?php

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

class IncompetenceFrustrationEvent extends MonthEndEvent
{
    public function getMinAge()
    {
        return 10;
    }

    public function getMinParticipants()
    {
        return 2;
    }

    public function getMaxParticipants()
    {
        return 2;
    }

    public function getCost()
    {
        return 20;
    }

    public function isAvailable()
    {
        $eligible = array_filter($this->tribe->getKobolds(), function ($kobold) {
            return $kobold->getAge() >= $this->getMinAge();
        });

        if (count($eligible) < 2) {
            return false;
        }

        foreach ($eligible as $kobold) {
            $statName = $kobold->getHighestStatName();
            $statValue = $statName ? $kobold->getStat($statName) : null;
            if ($statValue !== null && $statValue >= 50 && $statValue <= 60) {
                return true;
            }
        }

        return false;
    }

    private function ensureLikes($kobold)
    {
        if (!isset($kobold->dataStore)) {
            $kobold->dataStore = new stdClass();
        }
        if (!isset($kobold->dataStore->likes) || !is_array($kobold->dataStore->likes)) {
            $kobold->dataStore->likes = [];
        }
    }

    public function execute()
    {
        $kobolds = array_values($this->tribe->getKobolds());
        if (count($kobolds) < 2) {
            return;
        }

        $targets = array_values(array_filter($kobolds, function ($kobold) {
            $statName = $kobold->getHighestStatName();
            $statValue = $statName ? $kobold->getStat($statName) : null;
            return $statValue !== null && $statValue >= 50 && $statValue <= 60;
        }));

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

        $target = $targets[array_rand($targets)];
        $others = array_values(array_filter($kobolds, fn($k) => $k->getId() !== $target->getId()));
        if (empty($others)) {
            return;
        }

        $frustrated = $others[array_rand($others)];
        $statName = $target->getHighestStatName();

        $this->ensureLikes($frustrated);
        $current = $frustrated->dataStore->likes[$target->getId()] ?? 0;
        $frustrated->dataStore->likes[$target->getId()] = $current - 2;

        $variations = [
            "{$frustrated->getName()} grew frustrated with {$target->getName()}'s shaky {$statName} skills. The strain left a colder feeling between them.",
            "After another mistake from {$target->getName()}, {$frustrated->getName()} lost patience with {$target->getName()}'s {$statName} work.",
            "{$frustrated->getName()} watched {$target->getName()} struggle at {$statName} tasks and felt irritation build, dampening their goodwill."
        ];

        $this->story = $variations[array_rand($variations)];
        $frustrated->save();
    }
}
