<?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;

/**
 * Confirmation node processor for human-in-loop workflows.
 *
 * Pauses workflow execution and requests a Yes/No confirmation from the user.
 * When executed, it creates an interrupt request and throws
 * InterruptRequiredException to pause the workflow.
 *
 * The workflow resumes when the user responds, and this node outputs
 * whether the user confirmed or cancelled.
 *
 * Config:
 * - message: The confirmation message to display.
 * - confirm_label: Label for the confirm button (default: "Yes").
 * - cancel_label: Label for the cancel button (default: "No").
 *
 * Outputs:
 * - confirmed: Boolean indicating if the user confirmed.
 * - 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: "confirmation",
  label: new TranslatableMarkup("Confirmation"),
  description: "Pauses workflow for user confirmation (Yes/No)",
  version: "1.0.0"
)]
class ConfirmationNode 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);

    // Inject interrupt manager if available.
    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 {
    // Message is required.
    if (empty($params["message"])) {
      return ValidationResult::error("message", "Confirmation message is required.", "REQUIRED");
    }

    return ValidationResult::success();
  }

  /**
   * {@inheritdoc}
   */
  public function process(ParameterBagInterface $params): array {
    $message = $params->getString("message", "Do you want to continue?");
    $confirmLabel = $params->getString("confirm_label", "Yes");
    $cancelLabel = $params->getString("cancel_label", "No");

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

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

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

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

      if ($interrupt !== NULL && $interrupt->isResolved()) {
        // The interrupt has been resolved - return the result.
        return $this->buildOutputFromInterrupt($interrupt);
      }

      if ($interrupt !== NULL && $interrupt->isPending()) {
        // Still pending - throw exception again to keep waiting.
        throw new InterruptRequiredException(
          $interrupt,
          $this->buildExecutionContext(),
          "Waiting for user confirmation"
        );
      }

      // Interrupt was cancelled or expired.
      if ($interrupt !== NULL) {
        return [
          "confirmed" => FALSE,
          "response_time" => $interrupt->getResolvedAt() ?? time(),
          "user_id" => NULL,
          "status" => $interrupt->getStatus()->value,
          // Gateway output (for gateway mode flow control).
          "active_branches" => "false",
        ];
      }
    }

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

    // Get context from execution.
    $workflowId = "";
    $nodeId = "confirmation";
    $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;
    }

    // Create the interrupt with options for the buttons.
    $options = [
      ["value" => "true", "label" => $confirmLabel],
      ["value" => "false", "label" => $cancelLabel],
    ];

    $interrupt = $this->interruptManager->createInterrupt(
      InterruptType::Confirmation,
      $workflowId,
      $nodeId,
      $message,
    // No schema needed for confirmation.
      [],
      $options,
      $this->buildExecutionContext(),
    // No default value.
      NULL,
      $pipelineId,
      $sessionId,
    );

    // Throw exception to pause workflow.
    throw new InterruptRequiredException(
      $interrupt,
      $this->buildExecutionContext(),
      "Workflow paused for user confirmation"
    );
  }

  /**
   * Builds the output from a resolved interrupt.
   *
   * This method outputs both data values (confirmed, response_time, etc.)
   * and the active_branches value for gateway mode support. This enables
   * the Confirmation node to act as both a regular data node and a gateway
   * node for flow control.
   *
   * @param \Drupal\flowdrop_interrupt\Entity\FlowDropInterruptInterface $interrupt
   *   The resolved interrupt entity.
   *
   * @return array<string, mixed>
   *   The output array including both data outputs and active_branches.
   */
  protected function buildOutputFromInterrupt(FlowDropInterruptInterface $interrupt): array {
    $responseData = $interrupt->getResponseData();

    // Handle various response formats.
    $confirmed = FALSE;
    if (is_bool($responseData)) {
      $confirmed = $responseData;
    }
    elseif (is_string($responseData)) {
      $confirmed = strtolower($responseData) === "true" || $responseData === "1";
    }
    elseif (is_array($responseData) && isset($responseData["value"])) {
      $value = $responseData["value"];
      $confirmed = $value === TRUE || $value === "true" || $value === "1";
    }

    return [
      // Data outputs (for regular node mode).
      "confirmed" => $confirmed,
      "response_time" => $interrupt->getResolvedAt() ?? time(),
      "user_id" => $interrupt->getResolvedBy(),
      "interrupt_id" => $interrupt->uuid(),
      // Gateway output (for gateway mode flow control).
      "active_branches" => $confirmed ? "true" : "false",
    ];
  }

  /**
   * 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" => "Confirmation Message",
          "description" => "The message to display to the user",
          "default" => "Do you want to continue?",
          "format" => "multiline",
        ],
        "confirm_label" => [
          "type" => "string",
          "title" => "Confirm Button Label",
          "description" => "Label for the confirmation button",
          "default" => "Yes",
        ],
        "cancel_label" => [
          "type" => "string",
          "title" => "Cancel Button Label",
          "description" => "Label for the cancel button",
          "default" => "No",
        ],
        "__interrupt_id__" => [
          "type" => "string",
          "description" => "Internal: Interrupt ID for resume operations",
          "connectable" => FALSE,
          "configurable" => FALSE,
        ],
        // Branches parameter for gateway mode support.
        "branches" => [
          "type" => "array",
          "description" => "The available branches for gateway visual mode",
          "readOnly" => TRUE,
          "default" => [
            [
              "name" => "True",
              "value" => TRUE,
            ],
            [
              "name" => "False",
              "value" => FALSE,
            ],
          ],
          "items" => [
            "type" => "object",
            "properties" => [
              "name" => [
                "type" => "string",
                "description" => "The name of the branch",
              ],
              "value" => [
                "type" => "boolean",
                "description" => "The value of the branch",
              ],
            ],
          ],
        ],
      ],
      "required" => ["message"],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getOutputSchema(): array {
    return [
      "type" => "object",
      "properties" => [
        "confirmed" => [
          "type" => "boolean",
          "description" => "Whether the user confirmed (true) or cancelled (false)",
        ],
        "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",
        ],
        "active_branches" => [
          "type" => "string",
          "description" => "Gateway output: 'true' or 'false' for flow control in gateway mode",
        ],
      ],
    ];
  }

}
