<?php

namespace Drupal\ai_automators\PluginBaseClasses;

use Drupal\ai_automators\AiAutomatorInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * This is a base class that can be used for LLMs complex text chat.
 */
class ComplexTextChat extends RuleBase {

  /**
   * {@inheritDoc}
   */
  public function buildAdvancedConfigurationForm(array $form, FormStateInterface $form_state, AiAutomatorInterface $automator): array {
    $joiners = [
      '' => $this->t("-- Don't join --"),
      ', ' => $this->t('Comma, with space (, )'),
      ' ' => $this->t('Space ( )'),
      '. ' => $this->t('Period, with space (. )'),
      '\n' => $this->t('New line (\n)'),
      '\t' => $this->t('Tab (\t)'),
      '<br />' => $this->t('HTML Break (&#x3c;br />)'),
      '<br /><br />' => $this->t('HTML Double Break (&#x3c;br />&#x3c;br /&#x3e;)'),
      '<hr />' => $this->t('HTML Horizontal Rule (&#x3c;hr />)'),
      ',' => $this->t('Comma (,)'),
      ';' => $this->t('Semicolon (;)'),
      '.' => $this->t('Period (.)'),
      'other' => $this->t('Other'),
    ];

    $form['joiner'] = [
      '#type' => 'select',
      '#options' => $joiners,
      '#title' => $this->t('Joiner'),
      '#description' => $this->t('If you do not want multiple values back, this will take all values and join them.'),
      '#default_value' => $this->configuration['joiner'] ?? "",
    ];

    $form["joiner_other"] = [
      '#type' => 'textfield',
      '#title' => $this->t('Other Joiner'),
      '#description' => $this->t('If you selected other, please specify the joiner.'),
      '#default_value' => $this->configuration["joiner_other"] ?? "",
      '#states' => [
        'visible' => [
          'select[name="plugin_advanced[joiner]"]' => [
            'value' => 'other',
          ],
        ],
      ],
    ];
    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function generate(ContentEntityInterface $entity, FieldDefinitionInterface $fieldDefinition, array $automatorConfig) {
    // Generate the real prompt if needed.
    $prompts = parent::generate($entity, $fieldDefinition, $automatorConfig);

    // Add JSON output.
    foreach ($prompts as $key => $prompt) {
      $prompt .= "\n\nDo not include any explanations, only provide a RFC8259 compliant JSON response following this format without deviation.\n[{\"value\": \"requested value\"}]\n";
      $prompts[$key] = $prompt;
    }
    $total = [];
    $instance = $this->prepareLlmInstance('chat', $automatorConfig);
    foreach ($prompts as $prompt) {
      $values = $this->runChatMessage($prompt, $automatorConfig, $instance, $entity);

      if (!empty($values)) {
        $total = array_merge_recursive($total, $values);
      }
    }

    // If we should join, we do that.
    if (isset($automatorConfig['joiner']) && $automatorConfig['joiner']) {
      $joiner = $automatorConfig['joiner'];
      if ($joiner == 'other') {
        $joiner = $automatorConfig['joiner_other'];
      }
      // Reset values.
      $total = [$this->getGeneralHelper()->joinValues($total, $joiner)];
    }
    return $total;
  }

}
