<?php

declare(strict_types=1);

namespace Drupal\flowdrop_stategraph\Plugin\FlowDropNodeProcessor;

use Drupal\flowdrop\Attribute\FlowDropNodeProcessor;
use Drupal\flowdrop\DTO\ParameterBagInterface;
use Drupal\flowdrop\DTO\ValidationError;
use Drupal\flowdrop\DTO\ValidationResult;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\AbstractFlowDropNodeProcessor;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop_orchestration\DTO\Snapshot\IteratorState;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Iterator Next node processor.
 *
 * Advances the iterator to the next item and optionally records
 * the result from processing the previous item.
 *
 * Inputs:
 * - __iterator__: The current iterator state (injected from graph state).
 * - result: Optional result from processing the current item.
 *
 * Outputs:
 * - current_item: The next item to process.
 * - has_more: Whether more items remain after this one.
 * - is_exhausted: Whether the iterator has reached the end.
 * - state_update: StateUpdate to advance iterator in graph state.
 *
 * @internal This class is not part of the public API and may change without notice.
 */
#[FlowDropNodeProcessor(
  id: "iterator_next",
  label: new TranslatableMarkup("Iterator Next"),
  description: "Advances to the next item in iteration",
  version: "1.0.0"
)]
class IteratorNextNode extends AbstractFlowDropNodeProcessor {

  /**
   * {@inheritdoc}
   */
  public static function create(
    ContainerInterface $container,
    array $configuration,
    $plugin_id,
    $plugin_definition,
  ): static {
    return new static($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public function validateParams(array $params): ValidationResult {
    // Iterator state should be injected from graph state.
    if (!isset($params["__iterator__"])) {
      return ValidationResult::failure([
        new ValidationError('__iterator__', "Missing iterator state. This node must be used within a StateGraph execution."),
      ]);
    }

    return ValidationResult::success();
  }

  /**
   * {@inheritdoc}
   */
  public function process(ParameterBagInterface $params): array {
    $iteratorData = $params->get("__iterator__", []);
    $result = $params->get("result");

    // Reconstruct iterator state.
    $iterator = IteratorState::fromArray($iteratorData);

    // Add result if provided.
    if ($result !== NULL) {
      $iterator = $iterator->addResult($result);
    }

    // Advance to next item.
    $iterator = $iterator->advance();

    // Create state update.
    $stateUpdateData = [
      "iterator" => $iterator->toArray(),
    ];

    return [
      "current_item" => $iterator->currentItem,
      "current_index" => $iterator->currentIndex,
      "has_more" => $iterator->hasMore,
      "is_exhausted" => $iterator->isExhausted(),
      "remaining_count" => $iterator->getRemainingCount(),
      "results_count" => count($iterator->results),
      "state_update" => $stateUpdateData,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "__iterator__" => [
          "type" => "object",
          "description" => "Iterator state (injected from graph state)",
        ],
        "result" => [
          "type" => "mixed",
          "description" => "Result from processing the current item",
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getOutputSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "current_item" => [
          "type" => "mixed",
          "description" => "The next item to process",
        ],
        "current_index" => [
          "type" => "integer",
          "description" => "Current position in the array",
        ],
        "has_more" => [
          "type" => "boolean",
          "description" => "Whether more items remain",
        ],
        "is_exhausted" => [
          "type" => "boolean",
          "description" => "Whether iterator has reached the end",
        ],
        "remaining_count" => [
          "type" => "integer",
          "description" => "Number of remaining items",
        ],
        "results_count" => [
          "type" => "integer",
          "description" => "Number of collected results",
        ],
        "state_update" => [
          "type" => "object",
          "description" => "State update to apply to graph state",
        ],
      ],
    ];
  }

}
