<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\Plugin\FFmpegOutput;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\ffmpeg_media\Attribute\FFmpegOutput;
use Drupal\ffmpeg_media\ValueObject\ConversionOptions;

/**
 * JPEG-XL still image output format plugin.
 *
 * Captures a single representative frame from video as a high-quality
 * JPEG-XL still image. Encoding parameters (distance, effort, lossless)
 * are handled by the LibjxlCodec plugin.
 *
 * Animated JXL muxing is not yet supported in FFmpeg 8.x; this plugin
 * uses the image2 muxer with -frames:v 1 to produce a single frame.
 *
 * @see https://jpeg.org/jpegxl/
 */
#[FFmpegOutput(
  id: 'jxl',
  label: new TranslatableMarkup('JPEG XL'),
  description: new TranslatableMarkup('Next-generation image format with excellent compression. Captures a representative frame from video. Requires FFmpeg 8.0+ with libjxl.'),
  extension: 'jxl',
  mimeType: 'image/jxl',
  supportedCodecs: ['libjxl'],
  defaultCodec: 'libjxl',
  supportsAudio: FALSE,
  weight: 25,
)]
final class JxlOutput extends FFmpegOutputBase {

  /**
   * {@inheritdoc}
   */
  #[\Override]
  #[\NoDiscard]
  public function buildArguments(ConversionOptions $options): array {
    // Use image2 muxer with single-frame output.
    // Codec/quality args (-c:v, -distance, -effort) come from LibjxlCodec.
    return [
      '-frames:v', '1',
      '-update', '1',
      '-f', 'image2',
    ];
  }

  /**
   * {@inheritdoc}
   */
  #[\Override]
  #[\NoDiscard]
  public function generateOutputPath(string $inputPath): string {
    $pathInfo = pathinfo($inputPath);
    $baseName = $pathInfo['filename'] ?? 'image';
    $directory = $pathInfo['dirname'] ?? '';

    return $directory . DIRECTORY_SEPARATOR . $baseName . '_converted.jxl';
  }

}
