<?php

declare(strict_types=1);

namespace Drupal\native_observability_otel\Service;

use Drupal\Core\Config\ConfigFactoryInterface;

/**
 * Builds Prometheus-compatible metrics output from live source tables.
 */
final class PrometheusMetricsBuilder {

  /**
   * Default rolling window in seconds (5 minutes).
   */
  private const DEFAULT_WINDOW_SECONDS = 300;

  /**
   * Constructs the metrics builder.
   *
   * @param \Drupal\native_observability_otel\Service\LivePrometheusMetricsReader $liveReader
   *   The live metrics reader service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory.
   */
  public function __construct(
    private readonly LivePrometheusMetricsReader $liveReader,
    private readonly ConfigFactoryInterface $configFactory,
  ) {
  }

  /**
   * Builds Prometheus text exposition output from live source tables.
   *
   * @return string
   *   Prometheus-compatible plain text output.
   */
  public function build(): string {
    $windowSeconds = $this->resolveWindowSeconds();

    $parts = [];

    $parts[] = $this->liveReader->buildHttpMetrics($windowSeconds);

    $cacheMetrics = $this->liveReader->buildCacheMetrics();
    if ($cacheMetrics !== '') {
      $parts[] = $cacheMetrics;
    }

    $spanMetrics = $this->liveReader->buildSpanMetrics($windowSeconds);
    if ($spanMetrics !== '') {
      $parts[] = $spanMetrics;
    }

    return implode("\n", $parts);
  }

  /**
   * Resolves the rolling window seconds from config or falls back to default.
   *
   * @return int
   *   Window duration in seconds.
   */
  private function resolveWindowSeconds(): int {
    $window = (int) $this->configFactory
      ->get('native_observability_otel.settings')
      ->get('prometheus_window_seconds');

    return $window > 0 ? $window : self::DEFAULT_WINDOW_SECONDS;
  }

}
