<?php

namespace Drupal\api_monitor_ai\Form;

use Drupal\api_monitor_ai\AiAssistantService;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class SettingsForm extends ConfigFormBase {

  /**
   * Il servizio assistente AI.
   *
   * @var \Drupal\api_monitor_ai\AiAssistantService
   */
  protected $aiService;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->aiService = $container->get('api_monitor_ai.assistance_service');
    return $instance;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['api_monitor_ai.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'api_monitor_ai_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('api_monitor_ai.settings');

    $form['info'] = [
      '#type' => 'status_messages',
      '#markup' => $this->t('Questo modulo utilizza ora il provider AI di default configurato in <a href=":url">AI Providers</a>.', [
        ':url' => '/admin/config/ai/providers',
      ]),
    ];

    $form['heuristic_analysis'] = [
      '#type' => 'details',
      '#title' => $this->t('Analisi Euristica e PII Detection'),
      '#open' => TRUE,
    ];

    $form['heuristic_analysis']['heuristic_analysis_enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Abilita Analisi Euristica AI'),
      '#description' => $this->t('Analizza le risposte API per rilevare dati sensibili (PII) ed errori logici mascherati da 200 OK.'),
      '#default_value' => $config->get('heuristic_analysis_enabled'),
    ];

    $form['heuristic_analysis']['heuristic_analysis_sampling_rate'] = [
      '#type' => 'number',
      '#title' => $this->t('Percentuale di campionamento (%)'),
      '#min' => 1,
      '#max' => 100,
      '#description' => $this->t('Definisce con quale frequenza eseguire l\'analisi AI (es. 10 significa 1 analisi ogni 10 chiamate). Impostare a 100 per analizzare ogni chiamata.'),
      '#default_value' => $config->get('heuristic_analysis_sampling_rate') ?: 10,
      '#states' => [
        'visible' => [
          ':input[name="heuristic_analysis_enabled"]' => ['checked' => TRUE],
        ],
      ],
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('api_monitor_ai.settings')
      ->set('heuristic_analysis_enabled', $form_state->getValue('heuristic_analysis_enabled'))
      ->set('heuristic_analysis_sampling_rate', $form_state->getValue('heuristic_analysis_sampling_rate'))
      ->save();

    parent::submitForm($form, $form_state);
  }
}
