<?php

declare(strict_types=1);

namespace Drupal\native_observability_report\Service;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;

/**
 * Estimates the runtime overhead introduced by observability features.
 */
final class ObservabilityImpactEstimator {

  /**
   * Creates a new impact estimator instance.
   */
  public function __construct(
    private readonly ModuleHandlerInterface $moduleHandler,
    private readonly ConfigFactoryInterface $configFactory,
  ) {
  }

  /**
   * Builds a rough observability overhead estimate.
   *
   * @return array
   *   A normalized overhead payload.
   */
  public function estimate(): array {
    $estimatedPercent = 0.0;
    $contributors = [];

    if ($this->moduleHandler->moduleExists('native_observability_spans')) {
      $estimatedPercent += 5.0;
      $contributors[] = 'Trace and span collection';
    }

    if ($this->moduleHandler->moduleExists('native_observability_cache_observer')) {
      $estimatedPercent += 2.0;
      $contributors[] = 'Cache response and invalidation observation';
    }

    if ($this->moduleHandler->moduleExists('native_observability_database_observer')) {
      $estimatedPercent += 3.0;
      $contributors[] = 'Database query observation';
    }

    if ($this->moduleHandler->moduleExists('native_observability_logging')) {
      $estimatedPercent += 2.0;
      $contributors[] = 'Structured logging collection';
    }

    $level = 'low';
    if ($estimatedPercent >= 10.0) {
      $level = 'high';
    }
    elseif ($estimatedPercent >= 5.0) {
      $level = 'medium';
    }

    return [
      'estimated_overhead_percent' => round($estimatedPercent, 2),
      'impact_level' => $level,
      'contributors' => $contributors,
    ];
  }

}
