<?php

declare(strict_types=1);

namespace Drupal\flowdrop_interrupt\Plugin\FlowDropNodeProcessor;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\flowdrop\Attribute\FlowDropNodeProcessor;
use Drupal\flowdrop\DTO\ExecutionContextDTO;
use Drupal\flowdrop\DTO\ParameterBagInterface;
use Drupal\flowdrop\DTO\ValidationResult;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\AbstractFlowDropNodeProcessor;
use Drupal\flowdrop\Plugin\FlowDropNodeProcessor\ExecutionContextAwareInterface;
use Drupal\flowdrop_interrupt\Entity\FlowDropInterruptInterface;
use Drupal\flowdrop_interrupt\Enum\InterruptType;
use Drupal\flowdrop_interrupt\Exception\InterruptRequiredException;
use Drupal\flowdrop_interrupt\Service\InterruptManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Choice node processor for human-in-loop workflows.
 *
 * Pauses workflow execution and presents the user with a list of options
 * to choose from. Supports both single selection and multiple selection modes.
 *
 * Config:
 * - message: The prompt message to display.
 * - options: Array of options with value, label, and optional description.
 * - multiple: Whether to allow multiple selections (default: false).
 * - min_selections: Minimum number of selections required (default: 1).
 * - max_selections: Maximum number of selections allowed (optional).
 *
 * Outputs:
 * - selected: The selected value(s) - string for single, array for multiple.
 * - selection_count: Number of options selected.
 * - response_time: Timestamp when the response was received.
 * - user_id: ID of the user who responded (if authenticated).
 *
 * @internal This class is not part of the public API and may change without notice.
 */
#[FlowDropNodeProcessor(
  id: "choice_input",
  label: new TranslatableMarkup("Choice Input"),
  description: "Pauses workflow for user to select from options",
  version: "1.0.0"
)]
class ChoiceNode extends AbstractFlowDropNodeProcessor implements ExecutionContextAwareInterface {

  /**
   * The interrupt manager service.
   *
   * @var \Drupal\flowdrop_interrupt\Service\InterruptManagerInterface|null
   */
  protected ?InterruptManagerInterface $interruptManager = NULL;

  /**
   * The execution context.
   *
   * @var \Drupal\flowdrop\DTO\ExecutionContextDTO|null
   */
  protected ?ExecutionContextDTO $executionContext = NULL;

  /**
   * The logger service.
   *
   * @var \Psr\Log\LoggerInterface|null
   */
  protected ?LoggerInterface $logger = NULL;

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

    if ($container->has("flowdrop_interrupt.manager")) {
      $manager = $container->get("flowdrop_interrupt.manager");
      if ($manager instanceof InterruptManagerInterface) {
        $instance->interruptManager = $manager;
      }
    }

    $instance->logger = $container->get("logger.factory")->get("flowdrop_interrupt");

    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  public function setExecutionContext(ExecutionContextDTO $context): void {
    $this->executionContext = $context;
  }

  /**
   * {@inheritdoc}
   */
  public function validateParams(array $params): ValidationResult {
    if (empty($params["message"])) {
      return ValidationResult::error("message", "Prompt message is required.", "REQUIRED");
    }

    if (empty($params["options"]) || !is_array($params["options"])) {
      return ValidationResult::error("options", "At least one option is required.", "REQUIRED");
    }

    // Validate each option has value and label.
    foreach ($params["options"] as $index => $option) {
      if (!is_array($option)) {
        return ValidationResult::error("options", "Option {$index} must be an object.", "INVALID_TYPE");
      }
      if (empty($option["value"])) {
        return ValidationResult::error("options", "Option {$index} is missing a value.", "INVALID_OPTION");
      }
      if (empty($option["label"])) {
        return ValidationResult::error("options", "Option {$index} is missing a label.", "INVALID_OPTION");
      }
    }

    return ValidationResult::success();
  }

  /**
   * {@inheritdoc}
   */
  public function process(ParameterBagInterface $params): array {
    $message = $params->getString("message", "Please select an option");
    $options = $params->getArray("options", []);
    $multiple = $params->getBool("multiple", FALSE);
    $minSelections = $params->getInt("min_selections", 1);
    $maxSelections = $params->get("max_selections");

    if ($this->interruptManager === NULL) {
      throw new \RuntimeException(
        "InterruptManager service is not available. Ensure flowdrop_interrupt module is enabled."
      );
    }

    // Get context from execution.
    $workflowId = "";
    $nodeId = "choice_input";
    $pipelineId = NULL;
    $sessionId = NULL;

    if ($this->executionContext !== NULL) {
      $workflowId = $this->executionContext->getWorkflowId();
      $pipelineId = $this->executionContext->getPipelineId();
      $metadata = $this->executionContext->getMetadata();
      $nodeId = $metadata["node_id"] ?? $nodeId;
      $sessionId = isset($metadata["session_id"]) ? (int) $metadata["session_id"] : NULL;
    }

    // Check if we have a pending interrupt ID (explicit resume).
    $interruptId = $params->get("__interrupt_id__");

    // Debug logging to trace interrupt handling.
    $this->logger?->info("ChoiceNode: __interrupt_id__ = @id, nodeId = @nodeId, pipelineId = @pipelineId", [
      "@id" => $interruptId ?? "(null)",
      "@nodeId" => $nodeId,
      "@pipelineId" => $pipelineId ?? "(null)",
    ]);

    if ($interruptId !== NULL) {
      $interrupt = $this->interruptManager->getInterrupt((string) $interruptId);

      $this->logger?->info("ChoiceNode: Loaded interrupt (explicit) = @status", [
        "@status" => $interrupt !== NULL ? $interrupt->getStatus()->value : "(not found)",
      ]);

      if ($interrupt !== NULL && $interrupt->isResolved()) {
        return $this->buildOutputFromInterrupt($interrupt, $multiple);
      }

      if ($interrupt !== NULL && $interrupt->isPending()) {
        throw new InterruptRequiredException(
          $interrupt,
          $this->buildExecutionContext(),
          "Waiting for user selection"
        );
      }

      if ($interrupt !== NULL) {
        return [
          "selected" => $multiple ? [] : NULL,
          "selection_count" => 0,
          "response_time" => $interrupt->getResolvedAt() ?? time(),
          "user_id" => NULL,
          "status" => $interrupt->getStatus()->value,
        ];
      }
    }

    // Check for a resolved interrupt by pipeline and node (implicit resume).
    // This handles the case where the workflow is resumed and the interrupt ID
    // is not explicitly passed.
    if ($pipelineId !== NULL) {
      $resolvedInterrupt = $this->interruptManager->getResolvedInterruptForNode(
        $pipelineId,
        $nodeId
      );

      $this->logger?->info("ChoiceNode: Implicit lookup for pipeline @pipelineId, node @nodeId = @status", [
        "@pipelineId" => $pipelineId,
        "@nodeId" => $nodeId,
        "@status" => $resolvedInterrupt !== NULL ? $resolvedInterrupt->getStatus()->value : "(not found)",
      ]);

      if ($resolvedInterrupt !== NULL) {
        return $this->buildOutputFromInterrupt($resolvedInterrupt, $multiple);
      }
    }

    // Build schema with selection constraints.
    $schema = [
      "multiple" => $multiple,
      "minSelections" => $minSelections,
    ];
    if ($maxSelections !== NULL) {
      $schema["maxSelections"] = (int) $maxSelections;
    }

    $this->logger?->info("ChoiceNode: Creating NEW interrupt for node @nodeId (no resolved interrupt found)", [
      "@nodeId" => $nodeId,
    ]);

    $interrupt = $this->interruptManager->createInterrupt(
      InterruptType::Choice,
      $workflowId,
      $nodeId,
      $message,
      $schema,
      $options,
      $this->buildExecutionContext(),
      NULL,
      $pipelineId,
      $sessionId,
    );

    throw new InterruptRequiredException(
      $interrupt,
      $this->buildExecutionContext(),
      "Workflow paused for user selection"
    );
  }

  /**
   * Builds the output from a resolved interrupt.
   *
   * @param \Drupal\flowdrop_interrupt\Entity\FlowDropInterruptInterface $interrupt
   *   The resolved interrupt entity.
   * @param bool $multiple
   *   Whether multiple selections were allowed.
   *
   * @return array<string, mixed>
   *   The output array.
   */
  protected function buildOutputFromInterrupt(
    FlowDropInterruptInterface $interrupt,
    bool $multiple,
  ): array {
    $responseData = $interrupt->getResponseData();

    $this->logger?->info("ChoiceNode::buildOutputFromInterrupt: interrupt=@id, responseData=@data", [
      "@id" => $interrupt->uuid(),
      "@data" => is_array($responseData) ? json_encode($responseData) : (string) $responseData,
    ]);

    // Normalize response to expected format.
    $selected = $responseData;
    if ($multiple && !is_array($selected)) {
      $selected = $selected !== NULL ? [$selected] : [];
    }
    elseif (!$multiple && is_array($selected)) {
      $selected = !empty($selected) ? reset($selected) : NULL;
    }

    $selectionCount = is_array($selected) ? count($selected) : ($selected !== NULL ? 1 : 0);

    return [
      "selected" => $selected,
      "selection_count" => $selectionCount,
      "response_time" => $interrupt->getResolvedAt() ?? time(),
      "user_id" => $interrupt->getResolvedBy(),
      "interrupt_id" => $interrupt->uuid(),
    ];
  }

  /**
   * Builds the execution context for resuming.
   *
   * @return array<string, mixed>
   *   The execution context.
   */
  protected function buildExecutionContext(): array {
    $context = [];

    if ($this->executionContext !== NULL) {
      $context["workflow_id"] = $this->executionContext->getWorkflowId();
      $context["pipeline_id"] = $this->executionContext->getPipelineId();
      $context["metadata"] = $this->executionContext->getMetadata();
    }

    return $context;
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "message" => [
          "type" => "string",
          "title" => "Prompt Message",
          "description" => "The message to display to the user",
          "default" => "Please select an option",
          "format" => "multiline",
        ],
        "options" => [
          "type" => "array",
          "title" => "Options",
          "description" => "The options for the user to choose from",
          "items" => [
            "type" => "object",
            "properties" => [
              "value" => [
                "type" => "string",
                "title" => "Value",
                "description" => "The value returned when selected",
              ],
              "label" => [
                "type" => "string",
                "title" => "Label",
                "description" => "The display label for the option",
              ],
              "description" => [
                "type" => "string",
                "title" => "Description",
                "description" => "Optional description for the option",
              ],
            ],
            "required" => ["value", "label"],
          ],
        ],
        "multiple" => [
          "type" => "boolean",
          "title" => "Allow Multiple",
          "description" => "Allow selecting multiple options",
          "default" => FALSE,
        ],
        "min_selections" => [
          "type" => "integer",
          "title" => "Minimum Selections",
          "description" => "Minimum number of selections required",
          "default" => 1,
          "minimum" => 0,
        ],
        "max_selections" => [
          "type" => "integer",
          "title" => "Maximum Selections",
          "description" => "Maximum number of selections allowed (leave empty for no limit)",
          "minimum" => 1,
        ],
        "__interrupt_id__" => [
          "type" => "string",
          "description" => "Internal: Interrupt ID for resume operations",
          "connectable" => FALSE,
          "configurable" => FALSE,
        ],
      ],
      "required" => ["message", "options"],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getOutputSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "selected" => [
          "type" => "mixed",
          "description" => "The selected value(s) - string for single, array for multiple",
        ],
        "selection_count" => [
          "type" => "integer",
          "description" => "Number of options selected",
        ],
        "response_time" => [
          "type" => "integer",
          "description" => "Unix timestamp when the user responded",
        ],
        "user_id" => [
          "type" => "integer",
          "description" => "ID of the user who responded (null if anonymous)",
        ],
        "interrupt_id" => [
          "type" => "string",
          "description" => "UUID of the interrupt that was resolved",
        ],
      ],
    ];
  }

}
