<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\Form\SettingsTab;

use Drupal\Core\Config\Config;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\ffmpeg_media\FFmpegProcessorPluginManager;

/**
 * Builds the processors tab for the FFmpeg Media settings form.
 *
 * @internal
 */
final class ProcessorSettingsBuilder {

  use StringTranslationTrait;

  /**
   * Constructs a ProcessorSettingsBuilder.
   *
   * @param \Drupal\ffmpeg_media\FFmpegProcessorPluginManager $processorManager
   *   Processor plugin manager.
   */
  public function __construct(
    protected readonly FFmpegProcessorPluginManager $processorManager,
  ) {
  }

  /**
   * Builds the processors section render array.
   *
   * @param array<string, mixed> $form
   *   Form structure, passed by reference.
   * @param \Drupal\Core\Config\Config $config
   *   Module configuration.
   */
  public function build(array &$form, Config $config): void {
    $form['processors'] = [
      '#type' => 'details',
      '#title' => $this->t('Processors'),
      '#description' => $this->t('Processors run additional tasks after video conversion, such as generating thumbnails, extracting metadata, or creating subtitles.'),
      '#group' => 'settings_tabs',
      '#open' => FALSE,
    ];

    // Dynamically load available processors from plugin manager.
    $processorOptions = [];
    foreach ($this->processorManager->getDefinitions() as $id => $definition) {
      $label = $definition['label'] ?? $id;
      $processorOptions[$id] = $label instanceof TranslatableMarkup ? $label : $this->t('@label', ['@label' => $label]);
    }

    $form['processors']['enabled_processors'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Enabled processors'),
      '#description' => $this->t('Select which post-processing steps run after each video conversion. Disabled processors are skipped entirely.'),
      '#options' => $processorOptions,
      '#default_value' => $config->get('enabled_processors') ?? [],
    ];

    if (isset($processorOptions['whisper'])) {
      $this->buildWhisperProcessorHint($form);
    }
  }

  /**
   * Adds a contextual hint below the whisper processor checkbox.
   *
   * @param array<string, mixed> $form
   *   Form structure.
   */
  private function buildWhisperProcessorHint(array &$form): void {
    $whisperUrl = Url::fromRoute('ffmpeg_media_whisper.settings')->toString();
    $mediaTypesUrl = Url::fromRoute('entity.media_type.collection')->toString();

    $form['processors']['whisper_hint'] = [
      '#type' => 'container',
      '#attributes' => ['class' => ['messages', 'messages--info']],
      '#states' => [
        'visible' => [
          ':input[name="enabled_processors[whisper]"]' => ['checked' => TRUE],
        ],
      ],
      'message' => [
        '#type' => 'html_tag',
        '#tag' => 'div',
        '#value' => $this->t('Whisper generates subtitles (SRT/VTT) during conversion. Next steps: <ol><li>Configure model and language at <a href=":whisper_url">Whisper Settings</a>.</li><li>Configure transcript output in FFmpeg formatter settings under <a href=":media_types_url">Media types</a> (Manage display).</li><li>Use <code>drush ffmpeg:transcribe &lt;media_id&gt;</code> to transcribe existing videos.</li></ol>', [
          ':whisper_url' => $whisperUrl,
          ':media_types_url' => $mediaTypesUrl,
        ]),
      ],
    ];
  }

}
