// =============================================================================
// Format Utilities
// =============================================================================

import {
  FORMAT_METADATA,
  MIME_TO_FORMAT,
} from './types';
import type {
  SupportedFormat,
  FormatCategory,
  FormatMetadata,
  ImageFormat,
  AudioFormat,
} from './types';

/**
 * Detect format from a File's MIME type
 */
export function detectFormat(file: File): SupportedFormat | null {
  const format = MIME_TO_FORMAT[file.type];
  if (format) return format;

  // Fallback: try extension-based detection
  const ext = file.name.split('.').pop()?.toLowerCase();
  if (ext) {
    for (const [fmt, meta] of Object.entries(FORMAT_METADATA)) {
      if (meta.extension === ext || fmt === ext) {
        return fmt as SupportedFormat;
      }
    }
  }

  return null;
}

/**
 * Get the category (image or audio) for a format
 */
export function getFormatCategory(format: SupportedFormat): FormatCategory {
  return FORMAT_METADATA[format].category;
}

/**
 * Get format metadata
 */
export function getFormatMetadata(format: SupportedFormat): FormatMetadata {
  return FORMAT_METADATA[format];
}

/**
 * Get list of compatible output formats for a given input format.
 * Images can convert to other images, audio to other audio.
 */
export function getCompatibleOutputFormats(inputFormat: SupportedFormat): SupportedFormat[] {
  const category = getFormatCategory(inputFormat);

  return (Object.entries(FORMAT_METADATA) as [SupportedFormat, FormatMetadata][])
    .filter(([fmt, meta]) => meta.category === category && fmt !== inputFormat)
    .map(([fmt]) => fmt);
}

/**
 * Get all image formats
 */
export function getImageFormats(): ImageFormat[] {
  return (Object.entries(FORMAT_METADATA) as [SupportedFormat, FormatMetadata][])
    .filter(([, meta]) => meta.category === 'image')
    .map(([fmt]) => fmt as ImageFormat);
}

/**
 * Get all audio formats
 */
export function getAudioFormats(): AudioFormat[] {
  return (Object.entries(FORMAT_METADATA) as [SupportedFormat, FormatMetadata][])
    .filter(([, meta]) => meta.category === 'audio')
    .map(([fmt]) => fmt as AudioFormat);
}

/**
 * Check if a file is supported for conversion
 */
export function isSupported(file: File): boolean {
  return detectFormat(file) !== null;
}

/**
 * Generate output filename
 */
export function generateOutputFilename(originalName: string, targetFormat: SupportedFormat): string {
  const baseName = originalName.replace(/\.[^.]+$/, '');
  const ext = FORMAT_METADATA[targetFormat].extension;
  return `${baseName}.${ext}`;
}

/**
 * Generate unique ID for queue items
 */
export function generateId(): string {
  return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
}
