/**
 * Video source and player mode resolvers
 */

import type { VideoSourceUnion, PlayerMode, SimpleStreamSource, StreamSource, VideoPlayerContextValue } from '../types';

/**
 * Determine which provider to use based on source type
 */
export function resolvePlayerMode(
  source: VideoSourceUnion,
  mode: PlayerMode = 'auto'
): 'vidstack' | 'native' | 'streaming' {
  if (mode !== 'auto') {
    return mode;
  }

  switch (source.type) {
    case 'youtube':
    case 'vimeo':
    case 'hls':
    case 'dash':
      return 'vidstack';

    case 'stream':
    case 'blob':
      return 'streaming';

    case 'data-url':
    case 'url':
    default:
      return 'native';
  }
}

/**
 * Check if source is a simplified stream source (without getStreamUrl)
 */
export function isSimpleStreamSource(
  source: VideoSourceUnion | SimpleStreamSource | undefined | null
): source is SimpleStreamSource {
  return source != null && source.type === 'stream' && !('getStreamUrl' in source);
}

/**
 * Resolve simplified stream source to full stream source using context
 */
export function resolveStreamSource(
  source: SimpleStreamSource,
  context: VideoPlayerContextValue | null
): StreamSource | null {
  if (!context?.getStreamUrl) {
    console.warn(
      'VideoPlayer: Stream source requires getStreamUrl. ' +
      'Either provide it in source or wrap with VideoPlayerProvider.'
    );
    return null;
  }

  const sessionId = source.sessionId || context.sessionId;
  if (!sessionId) {
    console.warn('VideoPlayer: Stream source requires sessionId.');
    return null;
  }

  return {
    type: 'stream',
    sessionId,
    path: source.path,
    getStreamUrl: context.getStreamUrl,
    mimeType: source.mimeType,
    title: source.title,
    poster: source.poster,
  };
}
