<?php

namespace Drupal\api_monitor_client\Controller;

use Drupal\api_monitor_client\ApiSnifferService;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Url;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Controller for the status page.
 */
class StatusPageController extends ControllerBase {

  /**
   * Constructor StatusPageController.
   *
   * @param LoggerInterface $logger
   *   Logger instance for logging operations.
   * @param DateFormatterInterface $dateFormatter
   *   Formatter for date operations.
   * @param ApiSnifferService $apiSniffer
   *   Service for API sniffing operations.
   */
  public function __construct(
    private readonly LoggerInterface $logger,
    private readonly DateFormatterInterface $dateFormatter,
    private readonly ApiSnifferService $apiSniffer,
  ) {}

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('logger.channel.api_monitor_client'),
      $container->get('date.formatter'),
      $container->get('api_monitor_client.sniffer'),
    );
  }

  /**
   * Generates a table for API monitoring data.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return array
   *   A render array containing either a table of API monitoring data.
   */
  public function content(Request $request) :array {
    try {
      $provider_id = $request->query->get('provider');
      $results = $this->apiSniffer->retrieveApiRecords($provider_id, 50);

      $build = [];
      $build['filter_form'] = $this->formBuilder()->getForm('\Drupal\api_monitor_client\Form\StatusFilterForm');

      if (empty($results)) {
        $build['no_data'] = [
          '#markup' => '<p>' . $this->t('Non ci sono dati di monitoraggio disponibili.') . '</p>',
        ];
        return $build;
      }

      $header = [
        'Provider',
        'Servizio',
        'Endpoint ID',
        'Stato',
        'Tempo Risposta',
        'Uptime 24h',
        'Ultimo Check',
        'Operations',
      ];
      $rows = [];

      $providers = $this->entityTypeManager()->getStorage('api_monitor_provider')->loadMultiple();

      foreach ($results as $record) {
        $provider = $providers[$record->provider_id] ?? NULL;
        $rows[] = [
          'provider' => $provider ? $provider->label() : ($record->provider_id ?: '-'),
          'label' => $record->api_name ?? $record->api_id,
          'id' => $record->api_id,
          'status' => [
            'data' => [
              'indicator' => $this->buildStatusIndicator($record->status_code),
              'ai_indicator' => !empty($record->ai_verdict) ? $this->buildAiStatusIndicator($record->ai_verdict) : [],
              'code' => [
                '#markup' => ' <strong>' . ($record->status_code ?: 'N/A') . '</strong>',
              ],
            ],
          ],
          'time' => $record->response_time ? $record->response_time . 'ms' : '-',
          'uptime' => $this->apiSniffer->getUptime($record->api_id) . '%',
          'last_check' => $record->timestamp ? $this->dateFormatter
            ->format($record->timestamp, 'short') : '',
          'operations' => [
            'data' => [
              '#type' => 'operations',
              '#links' => [
                'detail' => [
                  'title' => $this->t('Dettaglio'),
                  'url' => Url::fromRoute('api_monitor_client.api_detail', [
                    'api_id' => $record->api_id,
                  ]),
                ],
                'swagger' => [
                  'title' => $this->t('Swagger'),
                  'url' => Url::fromRoute('api_monitor_client.swagger_ui', [
                    'provider_id' => $record->provider_id,
                    'api_id' => $record->api_id,
                  ]),
                ],
              ],
            ],
          ],
        ];

        // Add AI Assistance if module exists.
        if (\Drupal::moduleHandler()->moduleExists('api_monitor_ai')) {
           $rows[count($rows)-1]['operations']['data']['#links']['ai_assistance'] = [
              'title' => $this->t('AI Assistance'),
              'url' => Url::fromRoute('api_monitor_ai.assistant', [
                'api_id' => $record->api_id,
                'provider_id' => $record->provider_id,
              ]),
              'attributes' => [
                'class' => ['use-ajax'],
                'data-dialog-type' => 'modal',
                'data-dialog-options' => json_encode(['width' => 700]),
              ],
           ];
        }
      }

      $build['status_table'] = [
        '#type' => 'table',
        '#header' => $header,
        '#rows' => $rows,
        '#empty' => $this->t('Nessun dato di monitoraggio disponibile.'),
        '#cache' => [
          'tags' => ['api_monitor:status_page'],
          'contexts' => ['url.query_args:provider'],
        ],
      ];

      return $build;
    }
    catch (\Exception $e) {
      $this->logger->error('Errore nel recupero dei dati: ' . $e->getMessage());
      return [
        '#markup' => 'Errore nel recupero dei dati',
      ];
    }
  }

  /**
   * Builds a status indicator based on the provided status code.
   *
   * @param int $code
   *   The status code to determine the indicator color.
   *
   * @return array
   *   A renderable array with a color corresponding to the status code.
   */
  protected function buildStatusIndicator($code) {
    $color = '#ccc';
    if ($code >= 200 && $code < 300) {
      $color = '#28a745';
    }
    elseif ($code >= 400 && $code < 500) {
      $color = '#ffc107';
    }
    elseif ($code >= 500 || $code === 0) {
      $color = '#dc3545';
    }

    return [
      '#type' => 'html_tag',
      '#tag' => 'span',
      '#attributes' => [
        'style' => 'display:inline-block; width:12px; height:12px; border-radius:50%; background-color:' . $color . '; margin-right:8px;',
      ],
    ];
  }

  /**
   * Builds an AI status indicator based on the AI verdict.
   */
  protected function buildAiStatusIndicator($verdict) {
    $color = '#6c757d'; // Default gray
    $icon = '🤖';

    switch ($verdict) {
      case 'SAFE':
        $color = '#28a745'; // Green
        break;

      case 'WARNING':
        $color = '#ffc107'; // Yellow
        break;

      case 'CRITICAL':
        $color = '#dc3545'; // Red
        break;
    }

    return [
      '#type' => 'html_tag',
      '#tag' => 'span',
      '#value' => $icon,
      '#attributes' => [
        'title' => $this->t('AI Verdict: @verdict', ['@verdict' => $verdict]),
        'style' => 'display:inline-block; padding: 2px 4px; border-radius:4px; border: 1px solid ' . $color . '; color: ' . $color . '; font-size: 10px; margin-left: 8px; cursor: help;',
      ],
    ];
  }

}
