<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\Form\SettingsTab;

use Drupal\Core\Config\Config;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\ffmpeg_media\Service\FFmpegPathDetectorInterface;

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

  use StringTranslationTrait;

  /**
   * Constructs a FfmpegSettingsBuilder.
   *
   * @param \Drupal\ffmpeg_media\Service\FFmpegPathDetectorInterface $pathDetector
   *   Path detector service.
   */
  public function __construct(
    protected readonly FFmpegPathDetectorInterface $pathDetector,
  ) {
  }

  /**
   * Builds the FFmpeg executables 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['ffmpeg'] = [
      '#type' => 'details',
      '#title' => $this->t('Executables'),
      '#description' => $this->t('Server paths to FFmpeg and FFprobe binaries, execution timeouts, and caching. Only change paths if auto-detection fails.'),
      '#group' => 'settings_tabs',
    ];

    $detectedPaths = $this->pathDetector->detectPaths();

    $ffmpegDescription = $this->t('Absolute server path to the FFmpeg binary. Leave empty to auto-detect.');
    if ($detectedPaths['ffmpeg'] !== NULL) {
      $ffmpegDescription = $this->t('Absolute server path to the FFmpeg binary. Leave empty to auto-detect. Detected: <code>@path</code>', [
        '@path' => $detectedPaths['ffmpeg'],
      ]);
    }

    $form['ffmpeg']['ffmpeg_path'] = [
      '#type' => 'textfield',
      '#title' => $this->t('FFmpeg path'),
      '#description' => $ffmpegDescription,
      '#default_value' => $config->get('ffmpeg_path'),
      '#placeholder' => $detectedPaths['ffmpeg'] ?? '/usr/bin/ffmpeg',
    ];

    $ffprobeDescription = $this->t('Absolute server path to the FFprobe binary (used for reading video metadata). Leave empty to auto-detect.');
    if ($detectedPaths['ffprobe'] !== NULL) {
      $ffprobeDescription = $this->t('Absolute server path to the FFprobe binary (used for reading video metadata). Leave empty to auto-detect. Detected: <code>@path</code>', [
        '@path' => $detectedPaths['ffprobe'],
      ]);
    }

    $form['ffmpeg']['ffprobe_path'] = [
      '#type' => 'textfield',
      '#title' => $this->t('FFprobe path'),
      '#description' => $ffprobeDescription,
      '#default_value' => $config->get('ffprobe_path'),
      '#placeholder' => $detectedPaths['ffprobe'] ?? '/usr/bin/ffprobe',
    ];

    $form['ffmpeg']['ffprobe_cache_ttl'] = [
      '#type' => 'number',
      '#title' => $this->t('FFprobe cache TTL (seconds)'),
      '#description' => $this->t('Cache duration for video metadata (resolution, duration, codecs). Caching avoids repeated FFprobe calls for the same file. Set to 0 to disable.'),
      '#default_value' => $config->get('ffprobe_cache_ttl'),
      '#min' => 0,
      '#max' => 86400,
      '#required' => TRUE,
    ];

    $form['ffmpeg']['ffmpeg_timeout'] = [
      '#type' => 'number',
      '#title' => $this->t('FFmpeg timeout (seconds)'),
      '#description' => $this->t('Maximum time a single conversion may run before being terminated. Increase for very long videos or slow hardware.'),
      '#default_value' => $config->get('ffmpeg_timeout'),
      '#min' => 60,
      '#max' => 86400,
      '#required' => TRUE,
    ];

    $form['ffmpeg']['progress_update_interval'] = [
      '#type' => 'number',
      '#title' => $this->t('Progress update interval (seconds)'),
      '#description' => $this->t('How often the conversion progress percentage is updated in the database. Lower values give more responsive progress bars but increase database writes.'),
      '#default_value' => $config->get('progress_update_interval'),
      '#min' => 1,
      '#max' => 60,
      '#required' => TRUE,
    ];

    $form['ffmpeg']['progress_throttle_interval'] = [
      '#type' => 'number',
      '#title' => $this->t('Progress throttle interval (seconds)'),
      '#description' => $this->t('Minimum time between database writes for the same conversion. Reduces DB load during concurrent conversions (10+ simultaneous jobs). Status changes (e.g., converting to completed) are never throttled. Set to 0 to disable throttling.'),
      '#default_value' => $config->get('progress_throttle_interval') ?? 5,
      '#min' => 0,
      '#max' => 60,
      '#required' => TRUE,
    ];

    $form['ffmpeg']['active_count_cache_ttl'] = [
      '#type' => 'number',
      '#title' => $this->t('Active count cache TTL (seconds)'),
      '#description' => $this->t('How long the active conversion count is cached in memory before re-querying the database. Lower values increase accuracy but add database reads.'),
      '#default_value' => $config->get('active_count_cache_ttl') ?? 5.0,
      '#min' => 0,
      '#max' => 60,
      '#step' => 0.5,
      '#required' => TRUE,
    ];
  }

}
