<?php

namespace Drupal\api_monitor_ai\Hook;

use Drupal\Core\Hook\Attribute\Hook;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\api_monitor_client\ApiMonitorProbeManager;
use Drupal\Core\Queue\QueueFactory;

/**
 * Implements hook modules.
 */
final class ModuleHook {

  /**
   * Constructs a new ModuleHook object.
   */
  public function __construct(
    private readonly ConfigFactoryInterface $configFactory,
    private readonly ApiMonitorProbeManager $probeManager,
    private readonly QueueFactory $queueFactory,
  ) {}

  /**
   * Implements hook_api_monitor_history_insert().
   */
  #[Hook('api_monitor_history_insert')]
  public function apiMonitorHistoryInsert(int $history_id, array $result, string $api_id, string $provider_id): void {
    $config = $this->configFactory->get('api_monitor_ai.settings');
    if (!$config->get('heuristic_analysis_enabled')) {
      return;
    }

    $sampling_rate = $config->get('heuristic_analysis_sampling_rate') ?? 10;

    // Logica di campionamento casuale per risparmio token
    if (rand(1, 100) > $sampling_rate) {
      return;
    }

    // Solo se la chiamata è andata a buon fine tecnicamente
    if ($result['state'] === 'fulfilled' && isset($result['value'])) {
      /** @var \GuzzleHttp\Psr7\Response $response */
      $response = $result['value'];
      $body = (string) $response->getBody();
      $status_code = $response->getStatusCode();

      // Riavvolgiamo il body per i successivi utilizzi
      $response->getBody()->rewind();

      // Cerchiamo se esiste un plugin
      // per questo endpoint per vedere se le PII sono autorizzate
      $isPiiAuthorized = FALSE;
      $probes = $this->probeManager->getDefinitions();
      foreach ($probes as $plugin_id => $definition) {
        if ($definition['endpoint_id'] === $api_id) {
          $probe_instance = $this->probeManager->createInstance($plugin_id);
          if ($probe_instance) {
            $isPiiAuthorized = $probe_instance->isPiiAuthorized();
          }
          break;
        }
      }

      $truncatedBody = mb_strimwidth($body, 0, 3000, '...');

      // Inseriamo l'analisi in coda anziché eseguirla in modo sincrono.
      $queue = $this->queueFactory->get('api_monitor_ai_analysis');
      $queue->createItem([
        'history_id' => $history_id,
        'api_id' => $api_id,
        'body' => $truncatedBody,
        'status_code' => $status_code,
        'is_pii_authorized' => $isPiiAuthorized,
      ]);
    }
  }

  /**
   * Implements hook_theme().
   */
  #[Hook('theme')]
  public function theme(): array {
    return [
      'api_monitor_ai_chat' => [
        'variables' => [
          'title' => t('AI API Assistant'),
          'intro_text' => t('Chiedi informazioni sugli endpoint disponibili o come integrare le API.'),
          'api_id' => NULL,
          'provider_id' => NULL,
          'attributes' => NULL,
        ],
        'template' => 'api-monitor-ai-chat',
      ],
    ];
  }

}
