<?php

declare(strict_types=1);

namespace Drupal\flowdrop_node_processor\Plugin\FlowDropNodeProcessor;

use Drupal\flowdrop\Plugin\ExpressionEvaluator\ExpressionEvaluatorInterface;

/**
 * Provides expression evaluator integration for node processors.
 *
 * Classes using this trait must declare and assign the $evaluatorManager
 * property in their constructor:
 *
 * @code
 * public function __construct(
 *   ...
 *   protected readonly ExpressionEvaluatorPluginManager $evaluatorManager,
 * ) { ... }
 * @endcode
 *
 * @internal
 *   This trait is not part of the public API and may change without notice.
 */
trait ExpressionEvaluatorAwareTrait {

  /**
   * Parameter name for the expression engine selection.
   *
   * @var string
   */
  protected const ENGINE_PARAM = 'engine';

  /**
   * Get an evaluator instance for the given engine ID.
   *
   * @param string $engineId
   *   The expression evaluator plugin ID.
   *
   * @return \Drupal\flowdrop\Plugin\ExpressionEvaluator\ExpressionEvaluatorInterface
   *   The evaluator instance.
   *
   * @throws \RuntimeException
   *   If the engine ID is not recognized.
   */
  protected function getEvaluator(string $engineId): ExpressionEvaluatorInterface {
    try {
      return $this->evaluatorManager->createInstance($engineId);
    }
    catch (\Exception $e) {
      throw new \RuntimeException(
        "Unknown expression engine '{$engineId}': {$e->getMessage()}",
        0,
        $e
      );
    }
  }

  /**
   * Get available engine plugin IDs.
   *
   * @return array<int, string>
   *   List of available evaluator plugin IDs.
   */
  protected function getAvailableEngineIds(): array {
    return array_keys($this->evaluatorManager->getDefinitions());
  }

}
