/**
 * File source resolution utilities
 */

import type { VideoSourceUnion, ResolveFileSourceOptions } from '../types';

/**
 * Resolve file content to VideoSourceUnion
 * Useful for FileWorkspace/file manager integrations
 *
 * @example
 * const source = resolveFileSource({
 *   content: file.content,
 *   path: file.path,
 *   mimeType: file.mimeType,
 *   sessionId: sessionId,
 *   loadMethod: file.loadMethod,
 *   getStreamUrl: terminalClient.terminal_media.streamStreamRetrieveUrl
 * });
 *
 * <VideoPlayer source={source} />
 */
export function resolveFileSource(options: ResolveFileSourceOptions): VideoSourceUnion | null {
  const {
    content,
    path,
    mimeType,
    sessionId,
    loadMethod,
    getStreamUrl,
    title,
    poster,
  } = options;

  const contentSize = content
    ? typeof content === 'string'
      ? content.length
      : content.byteLength
    : 0;
  const hasContent = contentSize > 0;

  // Priority 1: HTTP Range streaming for large files
  if (loadMethod === 'http_stream' && !hasContent && sessionId && getStreamUrl) {
    return {
      type: 'stream',
      sessionId,
      path,
      getStreamUrl,
      mimeType,
      title,
      poster,
    };
  }

  // Priority 2: Data URL (base64 string)
  if (typeof content === 'string' && hasContent) {
    return {
      type: 'data-url',
      data: content,
      title,
      poster,
    };
  }

  // Priority 3: ArrayBuffer → Blob
  if (content instanceof ArrayBuffer && hasContent) {
    return {
      type: 'blob',
      data: content,
      mimeType: mimeType || 'video/mp4',
      title,
      poster,
    };
  }

  // No valid content
  return null;
}
