<?php
/**
 * Chatbot tool registry.
 *
 * @package KimaAI\ChatBot\Tools
 */

declare(strict_types=1);

namespace KimaAI\ChatBot\Tools;

defined('ABSPATH') || exit;

/**
 * Resolves chatbot tool settings into provider-ready tool definitions.
 */
final class ChatbotToolRegistry {

  /**
   * Resolve enabled tool names, per-tool config, and exposed provider definitions.
   *
   * @param array $payload Chatbot request payload.
   * @param array $chatbot_settings Chatbot settings.
   * @return array{payload: array, tools: array}
   */
  public function resolve(array $payload, array $chatbot_settings): array {
    $selected_tools = $chatbot_settings['allowedTools'] ?? [];

    if (!is_array($selected_tools)) {
      $selected_tools = [];
    }

    if (!empty($chatbot_settings['vectorDbEnabled'])) {
      $selected_tools[] = 'kb_vector_search';
      $payload['toolConfig']['kb_vector_search'] = [
        'env' => (string) ($chatbot_settings['vectorDbEnv'] ?? ''),
        'top_k' => (int) ($chatbot_settings['vectorDbTopK'] ?? 5),
        'min_score' => (float) ($chatbot_settings['vectorDbMinScore'] ?? 0.0),
      ];
    }

    $payload['selectedTools'] = apply_filters('kimaai_chatbot_allowed_tools', $selected_tools);

    if (!is_array($payload['selectedTools'])) {
      $payload['selectedTools'] = [];
    }

    /**
     * Filter: tools registry (add/modify/remove tools).
     *
     * @param array $tools The array of tool definitions.
     * @param array $payload The normalized chatbot payload.
     * @param array $chatbot_settings The chatbot settings.
     * @return array The modified array of tool definitions.
     */
    $tools = apply_filters('kimaai_chatbot_tools_registry', [], $payload, $chatbot_settings);
    $tools = is_array($tools) ? $tools : [];

    if (!empty($payload['selectedTools'])) {
      $allowed_names = array_flip($payload['selectedTools']);
      $tools = array_values(
        array_filter(
          $tools,
          static function ($tool) use ($allowed_names) {
            if (!is_array($tool) || empty($tool['name'])) {
              return false;
            }
            return isset($allowed_names[$tool['name']]);
          }
        )
      );
    }
    else {
      $tools = [];
    }

    return [
      'payload' => $payload,
      'tools' => $tools,
    ];
  }
}
