<?php

declare(strict_types=1);

namespace App\Framework\StateManagement;

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

/**
 * Statistics for state manager operations
 */
final readonly class StateManagerStatistics
{
    public function __construct(
        public int $totalKeys = 0,
        public int $hitCount = 0,
        public int $missCount = 0,
        public int $setCount = 0,
        public int $removeCount = 0,
        public int $updateCount = 0,
        public Duration $averageSetTime = new Duration(0.0),
        public Duration $averageGetTime = new Duration(0.0),
        public int $expiredKeys = 0,
        public Byte $memoryUsage = new Byte(0),
    ) {
    }

    /**
     * Calculate hit rate
     */
    public function getHitRate(): Percentage
    {
        $total = $this->hitCount + $this->missCount;
        if ($total === 0) {
            return Percentage::fromFloat(0.0);
        }

        return Percentage::fromFloat($this->hitCount / $total);
    }

    /**
     * Calculate miss rate
     */
    public function getMissRate(): Percentage
    {
        $hitRate = $this->getHitRate();

        return Percentage::fromFloat(1.0 - $hitRate->toFloat());
    }

    /**
     * Get total operations
     */
    public function getTotalOperations(): int
    {
        return $this->hitCount + $this->missCount + $this->setCount + $this->removeCount + $this->updateCount;
    }

    /**
     * Convert to array for serialization
     */
    public function toArray(): array
    {
        return [
            'total_keys' => $this->totalKeys,
            'hit_count' => $this->hitCount,
            'miss_count' => $this->missCount,
            'set_count' => $this->setCount,
            'remove_count' => $this->removeCount,
            'update_count' => $this->updateCount,
            'hit_rate' => $this->getHitRate()->toFloat(),
            'hit_rate_percentage' => $this->getHitRate()->toString(),
            'miss_rate' => $this->getMissRate()->toFloat(),
            'miss_rate_percentage' => $this->getMissRate()->toString(),
            'total_operations' => $this->getTotalOperations(),
            'average_set_time_ms' => $this->averageSetTime->toMilliseconds(),
            'average_get_time_ms' => $this->averageGetTime->toMilliseconds(),
            'expired_keys' => $this->expiredKeys,
            'memory_usage_bytes' => $this->memoryUsage->toBytes(),
            'memory_usage_mb' => $this->memoryUsage->toMegabytes(),
            'memory_usage_human' => $this->memoryUsage->toHumanReadable(),
        ];
    }
}
