<?php

declare(strict_types=1);

namespace Drupal\native_observability_metrics\Service;

/**
 * Calculates percentiles from numeric datasets.
 */
final class PercentileCalculator {

  /**
   * Calculates a percentile value.
   */
  public function calculate(array $values, int $percentile): float {
    if ($values === []) {
      return 0.0;
    }

    sort($values, SORT_NUMERIC);

    $index = ($percentile / 100) * (count($values) - 1);
    $lower = (int) floor($index);
    $upper = (int) ceil($index);

    if ($lower === $upper) {
      return (float) $values[$lower];
    }

    $weight = $index - $lower;

    return ((float) $values[$lower] * (1 - $weight)) + ((float) $values[$upper] * $weight);
  }

}
