<?php

namespace App\Framework\Cache\Strategies;

use App\Framework\Core\ValueObjects\Timestamp;

/**
 * Access pattern tracking for adaptive TTL calculation
 */
final class AccessPattern
{
    /** @var array<int, Timestamp> */
    private array $accessTimes = [];

    public function __construct(
        private readonly int $windowSize
    ) {}

    public function recordAccess(): void
    {
        $this->accessTimes[] = Timestamp::now();

        // Keep only recent accesses within the window
        if (count($this->accessTimes) > $this->windowSize) {
            array_shift($this->accessTimes);
        }
    }

    public function getRecentAccessCount(): int
    {
        return count($this->accessTimes);
    }

    public function getTotalAccesses(): int
    {
        return count($this->accessTimes);
    }

    /**
     * Calculate access frequency (accesses per hour)
     */
    public function getAccessFrequency(): float
    {
        if (count($this->accessTimes) < 2) {
            return 0.0;
        }

        $oldest = $this->accessTimes[0];
        $newest = end($this->accessTimes);
        $timeSpan = $newest->diff($oldest);

        if ($timeSpan->toSeconds() <= 0) {
            return 0.0;
        }

        $hours = $timeSpan->toSeconds() / 3600.0;

        return count($this->accessTimes) / $hours;
    }
}
