<?php

namespace Drupal\ai_automators\PluginBaseClasses;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;

/**
 * This is a base class that is for LLMs simple office hours field rules.
 */
class OfficeHours extends RuleBase {

  /**
   * {@inheritDoc}
   */
  public function helpText() {
    return "This can extract office hours from text.";
  }

  /**
   * {@inheritDoc}
   */
  public function placeholderText() {
    return "Based on the context text return the office hours that you can find.\n\nContext:\n{{ context }}";
  }

  /**
   * {@inheritDoc}
   */
  public function generate(ContentEntityInterface $entity, FieldDefinitionInterface $fieldDefinition, array $automatorConfig) {
    // Generate the real prompt if needed.
    $prompts = parent::generate($entity, $fieldDefinition, $automatorConfig);
    $this->setStructuredOutputSchema($entity, $fieldDefinition, $automatorConfig);
    $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);
      }
    }
    return $total;
  }

  /**
   * {@inheritDoc}
   */
  public function verifyValue(ContentEntityInterface $entity, $value, FieldDefinitionInterface $fieldDefinition, array $automatorConfig) {
    // Has to be valid day.
    if (!empty($value['day']) && !empty($value['starthours']) && !empty($value['endhours'])) {
      return TRUE;
    }
    // Otherwise it is not ok.
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  protected function getStructuredOutputValueSchema(ContentEntityInterface $entity, FieldDefinitionInterface $fieldDefinition, array $automatorConfig): array {
    return [
      'type' => 'object',
      'additionalProperties' => FALSE,
      'required' => [
        'day',
        'starthours',
        'endhours',
      ],
      'properties' => [
        'day' => [
          'type' => 'string',
          'pattern' => '^[1-7]$',
        ],
        'starthours' => [
          'type' => 'string',
          'pattern' => '^([01][0-9]|2[0-3])[0-5][0-9]$',
        ],
        'endhours' => [
          'type' => 'string',
          'pattern' => '^([01][0-9]|2[0-3])[0-5][0-9]$',
        ],
      ],
    ];
  }

}
