<?php

declare(strict_types=1);

class RankService
{
    public function generateRanks(array $results): array
    {
        if (empty($results)) {
            return [];
        }

        // Sort by percentage descending
        usort($results, static function ($a, $b) {
            return (float)$b['percentage'] <=> (float)$a['percentage'];
        });

        $rank = 1;
        $previousPercentage = null;
        $sameRankCount = 0;

        foreach ($results as $index => &$row) {
            $currentPercentage = (float)($row['percentage'] ?? 0);

            if ($previousPercentage !== null && $currentPercentage === $previousPercentage) {
                $row['rank_position'] = $rank;
                $sameRankCount++;
            } else {
                $rank += $sameRankCount;
                $row['rank_position'] = $rank;
                $sameRankCount = 1;
            }
            $previousPercentage = $currentPercentage;
        }
        unset($row);

        return $results;
    }
}