<?php

declare(strict_types=1);

namespace Drupal\native_observability_report\Service;

/**
 * Computes normalized statuses for report sections.
 */
final class ObservabilityScoringService {

  /**
   * Scores the overview section.
   */
  public function scoreOverview(array $overviewPayload): array {
    $requestTimeline = $overviewPayload['sections']['request_timeline'] ?? [];
    $technicalInsights = $overviewPayload['sections']['technical_insights'] ?? [];

    $slowRequestRate = (float) ($requestTimeline['summary']['slow_request_rate'] ?? 0.0);
    $attentionItems = is_array($technicalInsights['items'] ?? NULL) ? count($technicalInsights['items']) : 0;

    if ($slowRequestRate >= 25.0 || $attentionItems >= 4) {
      return $this->buildScore('critical', 35);
    }

    if ($slowRequestRate >= 10.0 || $attentionItems >= 2) {
      return $this->buildScore('warning', 68);
    }

    return $this->buildScore('good', 92);
  }

  /**
   * Scores the cache section.
   */
  public function scoreCache(array $cachePayload, bool $isProduction): array {
    $observability = $cachePayload['sections']['cache_observability'] ?? [];
    $summary = $observability['summary'] ?? [];

    $dynamicCacheEnabled = (bool) ($summary['dynamic_page_cache_enabled'] ?? FALSE);
    $hitRate = (float) ($summary['dynamic_cache_hit_rate'] ?? 0.0);

    if (!$dynamicCacheEnabled) {
      return $this->buildScore($isProduction ? 'critical' : 'warning', $isProduction ? 25 : 55);
    }

    if ($hitRate > 0 && $hitRate < 40.0) {
      return $this->buildScore('warning', 64);
    }

    return $this->buildScore('good', 90);
  }

  /**
   * Scores the database section.
   */
  public function scoreDatabase(array $databasePayload): array {
    $observability = $databasePayload['sections']['database_observability'] ?? [];
    $summary = $observability['summary'] ?? [];

    $averageDbTime = (float) ($summary['average_db_time_ms'] ?? 0.0);
    $slowIncidence = (float) ($summary['slow_query_incidence'] ?? 0.0);

    if ($averageDbTime >= 150.0 || $slowIncidence >= 25.0) {
      return $this->buildScore('critical', 30);
    }

    if ($averageDbTime >= 50.0 || $slowIncidence >= 10.0) {
      return $this->buildScore('warning', 66);
    }

    return $this->buildScore('good', 91);
  }

  /**
   * Builds a normalized score payload.
   */
  private function buildScore(string $status, int $score): array {
    return [
      'status' => $status,
      'score' => max(0, min(100, $score)),
      'severity' => match ($status) {
        'critical' => 3,
        'warning' => 2,
        default => 1,
      },
    ];
  }

}
