<?php

declare(strict_types=1);

namespace App\Framework\Console\Analytics\ValueObjects;

use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Core\ValueObjects\Percentage;

/**
 * Value object representing command popularity ranking
 */
final readonly class CommandPopularity
{
    public function __construct(
        public string $commandName,
        public int $rank,
        public int $totalExecutions,
        public Percentage $usagePercentage,
        public Duration $averageExecutionTime,
        public Percentage $successRate,
        public ?string $category = null
    ) {
    }

    public function isPopular(): bool
    {
        return $this->rank <= 10 || $this->usagePercentage->getValue() >= 5.0;
    }

    public function isRare(): bool
    {
        return $this->usagePercentage->getValue() < 0.5;
    }

    public function getPopularityLevel(): string
    {
        $usage = $this->usagePercentage->getValue();

        return match (true) {
            $usage >= 20 => 'very_high',
            $usage >= 10 => 'high',
            $usage >= 5 => 'medium',
            $usage >= 1 => 'low',
            default => 'very_low'
        };
    }

    public function toArray(): array
    {
        return [
            'command_name' => $this->commandName,
            'rank' => $this->rank,
            'total_executions' => $this->totalExecutions,
            'usage_percentage' => $this->usagePercentage->format(2),
            'usage_percentage_value' => $this->usagePercentage->getValue(),
            'average_execution_time' => $this->averageExecutionTime->toHumanReadable(),
            'success_rate' => $this->successRate->format(1),
            'success_rate_value' => $this->successRate->getValue(),
            'category' => $this->category,
            'popularity_level' => $this->getPopularityLevel(),
            'is_popular' => $this->isPopular(),
            'is_rare' => $this->isRare(),
        ];
    }
}
