/**
 * Image utility functions for metadata processing
 */

interface StandardRatio {
  ratio: string;
  decimal: number;
  tolerance: number;
}

const STANDARD_RATIOS: StandardRatio[] = [
  { ratio: '1:1', decimal: 1.0, tolerance: 0.02 }, // Square
  { ratio: '4:3', decimal: 1.333, tolerance: 0.02 }, // Standard
  { ratio: '3:2', decimal: 1.5, tolerance: 0.02 }, // Classic photo
  { ratio: '16:10', decimal: 1.6, tolerance: 0.02 }, // Common monitor
  { ratio: '16:9', decimal: 1.778, tolerance: 0.02 }, // Widescreen
  { ratio: '21:9', decimal: 2.333, tolerance: 0.02 }, // Ultrawide
  { ratio: '9:16', decimal: 0.5625, tolerance: 0.02 }, // Vertical video
  { ratio: '2:3', decimal: 0.667, tolerance: 0.02 }, // Portrait photo
  { ratio: '3:4', decimal: 0.75, tolerance: 0.02 }, // Portrait standard
];

/**
 * Calculate aspect ratio with tolerance for standard ratios
 * @param width - Image width in pixels
 * @param height - Image height in pixels
 * @returns Aspect ratio as string (e.g., "16:9" or "1.78")
 */
export const calculateAspectRatio = (width: number, height: number): string => {
  const decimal = width / height;

  // Check if it matches a standard ratio within tolerance
  for (const standard of STANDARD_RATIOS) {
    const diff = Math.abs(decimal - standard.decimal) / standard.decimal;
    if (diff <= standard.tolerance) {
      return standard.ratio;
    }
  }

  // If no match, return decimal with 2 places
  return decimal.toFixed(2);
};

/**
 * Format file size in human-readable format
 * @param bytes - File size in bytes
 * @returns Formatted string (e.g., "2.4 MB")
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
};

/**
 * Extract file type from MIME type
 * @param contentType - MIME type (e.g., "image/png")
 * @returns File type (e.g., "PNG")
 */
export const getFileTypeFromMimeType = (contentType: string): string => {
  const type = contentType.split('/')[1];
  return type ? type.toUpperCase() : 'UNKNOWN';
};

/**
 * Format duration in milliseconds to human-readable format
 * @param ms - Duration in milliseconds
 * @returns Formatted string (e.g., "143ms" or "1.23s")
 */
export const formatDuration = (ms: number): string => {
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(2)}s`;
};
