<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\VideoFilter;

/**
 * Represents a video filter contribution from a filter provider.
 *
 * Encapsulates both the filter_complex string and any additional FFmpeg
 * inputs required (e.g., a watermark image as a second input).
 */
final readonly class VideoFilterResult {

  /**
   * The filter_complex fragment.
   */
  public string $filterComplex;

  /**
   * Additional FFmpeg input paths.
   *
   * @var array<int, string>
   */
  public array $extraInputs;

  /**
   * Placeholder labels for extra inputs.
   *
   * @var array<int, string>
   */
  public array $extraInputLabels;

  /**
   * Constructs a VideoFilterResult.
   *
   * @param string $filterComplex
   *   The filter_complex fragment. Must use [video_in] as its input label
   *   and produce [video_out] as its output label. The collector chains
   *   these labels between providers.
   * @param array<int, string> $extraInputs
   *   Additional input file paths to add as -i arguments before the
   *   filter_complex. E.g., a watermark PNG.
   * @param array<int, string> $extraInputLabels
   *   Placeholder labels used inside the filter graph for each extra input.
   *   The order must match $extraInputs. When omitted, legacy-compatible
   *   defaults are generated.
   */
  public function __construct(
    string $filterComplex,
    array $extraInputs = [],
    array $extraInputLabels = [],
  ) {
    $this->filterComplex = $filterComplex;
    $this->extraInputs = array_values($extraInputs);

    if ($this->extraInputs === []) {
      $this->extraInputLabels = [];
      return;
    }

    if ($extraInputLabels === []) {
      $this->extraInputLabels = self::buildDefaultLabels(count($this->extraInputs));
      return;
    }

    if (count($extraInputLabels) !== count($this->extraInputs)) {
      throw new \InvalidArgumentException('extraInputLabels must match extraInputs by position.');
    }

    $this->extraInputLabels = array_values($extraInputLabels);
  }

  /**
   * Builds default placeholder labels for legacy provider results.
   *
   * @param int $count
   *   Number of extra inputs.
   *
   * @return array<int, string>
   *   Placeholder labels.
   */
  private static function buildDefaultLabels(int $count): array {
    $labels = [];
    for ($index = 0; $index < $count; $index++) {
      $labels[] = $index === 0
        ? '[wm_in]'
        : sprintf('[extra_input_%d]', $index);
    }

    return $labels;
  }

}
