<?php

declare(strict_types=1);

namespace Drupal\api_monitor_ai\Plugin\QueueWorker;

use Drupal\api_monitor_ai\AiAssistantService;
use Drupal\api_monitor_client\Alert\AlertManager;
use Drupal\Core\Database\Connection;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Queue\Attribute\QueueWorker;
use Drupal\Core\Queue\QueueWorkerBase;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Processes API response analysis using AI.
 */
#[QueueWorker(
  id: 'api_monitor_ai_analysis',
  title: new TranslatableMarkup('API Monitor AI Analysis'),
  cron: ['time' => 30]
)]
final class ApiMonitorAiAnalysisQueueWorker extends QueueWorkerBase implements ContainerFactoryPluginInterface {

  /**
   * Constructs a new ApiMonitorAiAnalysisQueueWorker object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\api_monitor_ai\AiAssistantService $aiAssistant
   *   The AI Assistant service.
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection.
   * @param \Drupal\api_monitor_client\Alert\AlertManager $alertManager
   *   The alert manager service.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    private readonly AiAssistantService $aiAssistant,
    private readonly Connection $database,
    private readonly AlertManager $alertManager,
    private readonly LoggerInterface $logger,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self {
    return new self(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('api_monitor_ai.assistance_service'),
      $container->get('database'),
      $container->get('api_monitor_client.alert_manager'),
      $container->get('logger.channel.api_monitor_ai')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($data): void {
    $history_id = $data['history_id'] ?? NULL;
    $api_id = $data['api_id'] ?? NULL;
    $body = $data['body'] ?? '';
    $status_code = $data['status_code'] ?? 200;
    $is_pii_authorized = $data['is_pii_authorized'] ?? FALSE;

    if (!$history_id || !$api_id) {
      $this->logger->error('Dati non validi per la coda di analisi AI: manca history_id o api_id.');
      return;
    }

    // Eseguiamo l'analisi euristica con l'IA
    $analysis = $this->aiAssistant->analyzeResponseHealth($api_id, $body, (int) $status_code, (bool) $is_pii_authorized);

    if (isset($analysis['error'])) {
      $this->logger->error('Errore durante l\'analisi AI per il record @id: @error', [
        '@id' => $history_id,
        '@error' => $analysis['error'],
      ]);
      
      // Se è un errore di parsing JSON (e non un timeout/errore di rete), non riproviamo per non bloccare la coda
      if (str_contains($analysis['error'], 'non è un JSON valido')) {
        $this->database->update('api_monitor_history')
          ->fields([
            'ai_verdict' => 'ERROR',
            'ai_metadata' => json_encode(['error' => $analysis['error']]),
          ])
          ->condition('id', $history_id)
          ->execute();
        return;
      }
      
      throw new \RuntimeException("Errore temporaneo o di rete durante l'analisi AI: " . $analysis['error']);
    }

    $verdict = $analysis['verdict'] ?? 'UNKNOWN';

    // Aggiorna il record di storico nel database con il responso dell'IA
    $this->database->update('api_monitor_history')
      ->fields([
        'ai_verdict' => $verdict,
        'ai_metadata' => json_encode($analysis),
      ])
      ->condition('id', $history_id)
      ->execute();

    // Se il verdetto è CRITICAL, invia la notifica/alert
    if ($verdict === 'CRITICAL') {
      $this->alertManager->notify($api_id, 'AI_CRITICAL_ALERT', [
        'issues' => $analysis['issues'] ?? [],
        'summary' => $analysis['analysis_summary'] ?? '',
      ]);
    }
  }

}
