import type { StreamSelection } from '../commands/command-utils';
import type { MediaProbe, MediaStreamProbe } from '../media';
import type { ExportPreset } from '../commands/convert';

export type QuickOperation = 'convert' | 'remux';

export function defaultQuickStreamSelection(
  probe: MediaProbe,
  operation: QuickOperation,
  preset: ExportPreset | undefined
): StreamSelection {
  const selected = probe.streams.filter(
    (stream) =>
      quickStreamUnavailableReason(stream, operation, preset) === undefined
  );
  return {
    video: selected
      .filter((stream) => stream.type === 'video')
      .map((stream) => stream.index),
    audio: selected
      .filter((stream) => stream.type === 'audio')
      .map((stream) => stream.index),
    subtitles: selected
      .filter((stream) => stream.type === 'subtitle')
      .map((stream) => stream.index),
    attachments: selected
      .filter((stream) => stream.type === 'attachment')
      .map((stream) => stream.index),
    data: selected
      .filter((stream) => stream.type === 'data')
      .map((stream) => stream.index),
  };
}

export function quickStreamUnavailableReason(
  stream: MediaStreamProbe,
  operation: QuickOperation,
  preset: ExportPreset | undefined
): string | undefined {
  if (stream.type === 'unknown') {
    return 'unknown stream kinds cannot be mapped safely.';
  }
  if (operation === 'remux') {
    return undefined;
  }
  if (!preset) {
    return 'choose an export preset first.';
  }
  if (stream.type === 'video' && !preset.video) {
    return 'the selected preset creates audio only.';
  }
  if (stream.type === 'audio' && !preset.audio) {
    return 'the selected preset creates video or images without audio.';
  }
  if (stream.type === 'subtitle') {
    if (preset.subtitlePolicy === 'none') {
      return 'the selected preset explicitly omits subtitles.';
    }
    if (preset.subtitlePolicy === 'burn-in') {
      return 'burn-in requires an explicitly attached subtitle source.';
    }
  }
  if (
    (stream.type === 'attachment' || stream.type === 'data') &&
    preset.container !== 'matroska'
  ) {
    return `${stream.type} streams are only preserved by the reviewed Matroska conversion path.`;
  }
  return undefined;
}
