<?php

declare(strict_types=1);

namespace Drupal\native_observability_otel\Service;

use Drupal\native_observability_otel\Plugin\NativeObservabilityExporter\ExporterInterface;
use Drupal\native_observability_otel\PluginManager\ExporterManager;

/**
 * Provides helper methods to access exporter plugins.
 */
class ExporterRegistry {

  /**
   * The exporter manager.
   */
  protected ExporterManager $exporterManager;

  /**
   * Constructs a new ExporterRegistry instance.
   *
   * @param \Drupal\native_observability_otel\PluginManager\ExporterManager $exporter_manager
   *   The exporter manager.
   */
  public function __construct(ExporterManager $exporter_manager) {
    $this->exporterManager = $exporter_manager;
  }

  /**
   * Returns all exporter definitions.
   *
   * @return array
   *   The exporter plugin definitions.
   */
  public function getDefinitions(): array {
    return $this->exporterManager->getDefinitions();
  }

  /**
   * Returns a single exporter instance by plugin ID.
   *
   * @param string $plugin_id
   *   The plugin ID.
   *
   * @return \Drupal\native_observability_otel\Plugin\NativeObservabilityExporter\ExporterInterface
   *   The exporter instance.
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginException
   */
  public function get(string $plugin_id): ExporterInterface {
    /** @var \Drupal\native_observability_otel\Plugin\NativeObservabilityExporter\ExporterInterface $plugin */
    $plugin = $this->exporterManager->createInstance($plugin_id);
    return $plugin;
  }

  /**
   * Returns all available exporter instances.
   *
   * @return \Drupal\native_observability_otel\Plugin\NativeObservabilityExporter\ExporterInterface[]
   *   The available exporters keyed by plugin ID.
   */
  public function getAvailableExporters(): array {
    $exporters = [];

    foreach (array_keys($this->exporterManager->getDefinitions()) as $plugin_id) {
      $exporter = $this->get($plugin_id);

      if ($exporter->isAvailable()) {
        $exporters[$plugin_id] = $exporter;
      }
    }

    return $exporters;
  }

}
