<?php

declare(strict_types=1);

namespace Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor;

use Drupal\Core\StringTranslation\TranslatableMarkup;
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\flowdrop\Plugin\FlowDropNodeProcessor\ExecutionContextAwareInterface;
use Drupal\flowdrop_memory\Service\MemoryManager;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Context-aware memory delete node processor.
 *
 * Deletes a single key from the configured memory backend. The scope ID is
 * automatically derived from the current execution context.
 *
 * To delete an entire scope (e.g., clear all conversation history), use
 * the key '__scope__' as a convention and handle it in a custom processor,
 * or call MemoryManager::clearScope() programmatically.
 *
 * @see \Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\MemoryDeleteRaw
 * @see \Drupal\flowdrop_memory\Plugin\FlowDropNodeProcessor\ConversationBuffer
 */
#[FlowDropNodeProcessor(
  id: 'memory_delete',
  label: new TranslatableMarkup('Memory Delete'),
  description: 'Delete a key from scoped memory. Scope ID is automatically derived from the execution context.',
  version: '1.0.0',
)]
class MemoryDelete extends AbstractFlowDropNodeProcessor implements ExecutionContextAwareInterface {

  use ScopeResolutionTrait;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    array $configuration,
    string $plugin_id,
    mixed $plugin_definition,
    private readonly MemoryManager $memoryManager,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): static {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('flowdrop_memory.manager'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function validateParams(array $params): ValidationResult {
    $errors = [];
    if (empty($params['key'])) {
      $errors[] = new ValidationError('key', 'Memory key is required.');
    }
    return empty($errors) ? ValidationResult::success() : ValidationResult::failure($errors);
  }

  /**
   * {@inheritdoc}
   */
  public function process(ParameterBagInterface $params): array {
    $scope = $params->getString('scope', 'global');
    $key = $params->getString('key');
    $backend = $params->getString('backend', 'static');

    $resolvedScopeId = $this->resolveScopeId($scope);
    $this->memoryManager->delete($scope, $resolvedScopeId, $key, $backend);

    return [
      'success'           => TRUE,
      'key'               => $key,
      'scope'             => $scope,
      'resolved_scope_id' => $resolvedScopeId,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getParameterSchema(): array {
    return [
      'type' => 'object',
      'properties' => [
        'scope' => [
          'type'        => 'string',
          'title'       => 'Scope',
          'description' => 'The memory scope.',
          'enum'        => ['global', 'workflow', 'pipeline', 'execution', 'session'],
          'default'     => 'global',
        ],
        'key' => [
          'type'        => 'string',
          'title'       => 'Key',
          'description' => 'The memory key to delete.',
        ],
        'backend' => [
          'type'        => 'string',
          'title'       => 'Memory Backend',
          'description' => 'The storage backend to use.',
          'enum'        => ['static', 'cached', 'entity'],
          'default'     => 'static',
        ],
      ],
      'required' => ['key', 'backend'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getOutputSchema(): array {
    return [
      'type' => 'object',
      'properties' => [
        'success' => [
          'type'        => 'boolean',
          'description' => 'Always TRUE when the delete completes (even if the key did not exist).',
        ],
        'key' => [
          'type'        => 'string',
          'description' => 'The key that was deleted.',
        ],
        'scope' => [
          'type'        => 'string',
          'description' => 'The scope used.',
        ],
        'resolved_scope_id' => [
          'type'        => 'string',
          'description' => 'The scope ID that was actually used (after auto-resolution).',
        ],
      ],
    ];
  }

}
