import { getLanguageLabel } from '../../utils/language';
import type { Job, JobDownloadsResponse, LangOutput } from '../../types/api';

export interface AssetTab {
  key: string;           // e.g., "en", "en_accessible"
  label: string;         // e.g., "English", "English Accessible"
  isAccessible: boolean;
  language: string;      // Base language code
  videoUrl: string;      // Source video or accessible video URL
  captionsVttField: 'captions_vtt_gcs' | 'retimed_captions_vtt_gcs';
}

/**
 * Build the list of asset tabs from job data.
 * - One tab per language (standard video with that language's captions)
 * - One tab per accessible video if it exists
 */
export function buildAssetTabs(
  job: Job,
  downloads: JobDownloadsResponse | undefined
): AssetTab[] {
  const tabs: AssetTab[] = [];
  const outputs = job.outputs || {};

  // Get source video URL
  const sourceVideoUrl = downloads?.downloads?.source_video as string | undefined;

  for (const [lang, output] of Object.entries(outputs) as [string, LangOutput][]) {
    const langDownloads = downloads?.downloads?.[lang] as Record<string, string> | undefined;

    // Standard language tab (uses source video)
    if (sourceVideoUrl) {
      tabs.push({
        key: lang,
        label: getLanguageLabel(lang),
        isAccessible: false,
        language: lang,
        videoUrl: sourceVideoUrl,
        captionsVttField: 'captions_vtt_gcs',
      });
    }

    // Accessible video tab (if exists)
    if (output.accessible_video_gcs && langDownloads?.accessible_video_mp4) {
      tabs.push({
        key: `${lang}_accessible`,
        label: `${getLanguageLabel(lang)} Accessible`,
        isAccessible: true,
        language: lang,
        videoUrl: langDownloads.accessible_video_mp4,
        // Use retimed captions for pause-insert method, fall back to regular captions
        captionsVttField: output.retimed_captions_vtt_gcs
          ? 'retimed_captions_vtt_gcs'
          : 'captions_vtt_gcs',
      });
    }
  }

  return tabs;
}
