/**
 * 批量缩略图生成器类型定义
 * 遵循 Tauri 开发规范的类型系统设计
 */

// 时间点配置
export type TimePoint = 
  | { Fixed: number }                    // 固定时间点（秒）
  | { Percentage: number }               // 百分比位置 (0.0-1.0)
  | { Multiple: number[] }               // 多个时间点
  | { SmartDetection: number };          // 智能场景检测（帧数）

// 预设尺寸
export enum SizePreset {
  Tiny = 'Tiny',       // 160x120
  Small = 'Small',     // 320x240
  Medium = 'Medium',   // 640x480
  Large = 'Large',     // 1280x720
  FullHD = 'FullHD',   // 1920x1080
  Custom = 'Custom',   // 自定义尺寸
}

// 缩略图尺寸配置
export interface ThumbnailSize {
  width: number;
  height: number;
  preset?: SizePreset;
}

// 图片格式
export enum ImageFormat {
  Jpg = 'Jpg',
  Png = 'Png',
  WebP = 'WebP',
}

// 缩略图生成配置
export interface ThumbnailConfig {
  time_points: TimePoint[];
  size: ThumbnailSize;
  format: ImageFormat;
  quality: number;
  output_dir: string;
  naming_pattern: string;
  preserve_aspect_ratio: boolean;
}

// 时间轴布局
export type TimelineLayout = 
  | 'Horizontal'
  | 'Vertical'
  | { Grid: { columns: number } };

// 时间轴缩略图配置
export interface TimelineConfig {
  frame_count: number;
  layout: TimelineLayout;
  show_timestamps: boolean;
  spacing: number;
  background_color?: string;
  border_width?: number;
}

// 任务状态
export enum TaskStatus {
  Pending = 'Pending',    // 等待中
  Running = 'Running',    // 执行中
  Completed = 'Completed', // 已完成
  Failed = 'Failed',      // 失败
  Cancelled = 'Cancelled', // 已取消
  Paused = 'Paused',      // 已暂停
}

// 缩略图元数据
export interface ThumbnailMetadata {
  video_duration: number;
  video_resolution: [number, number];
  thumbnail_count: number;
  total_file_size: number;
  timestamps_used: number[];
}

// 缩略图生成结果
export interface ThumbnailGenerationResult {
  video_path: string;
  success: boolean;
  output_paths: string[];
  timeline_path?: string;
  processing_time_ms: number;
  error_message?: string;
  metadata: ThumbnailMetadata;
}

// 批量处理进度
export interface BatchProgress {
  total_files: number;
  processed_files: number;
  failed_files: number;
  current_file?: string;
  progress_percentage: number;
  estimated_remaining_ms?: number;
  processing_speed?: number; // 文件/秒
  errors: string[];
  results: ThumbnailGenerationResult[];
}

// 批量缩略图任务
export interface BatchThumbnailTask {
  task_id: string;
  video_files: string[];
  config: ThumbnailConfig;
  timeline_config?: TimelineConfig;
  status: TaskStatus;
  progress: BatchProgress;
  created_at: string;
  updated_at: string;
  started_at?: string;
  completed_at?: string;
}

// 视频文件信息
export interface VideoFile {
  path: string;
  name: string;
  size: number;
  duration?: number;
  resolution?: [number, number];
  format?: string;
  is_valid: boolean;
}

// 场景信息
export interface SceneInfo {
  start_time: number;
  end_time: number;
  duration: number;
  confidence: number;
  representative_frame: number;
}

// 场景检测方法
export enum SceneDetectionMethod {
  ContentBased = 'ContentBased',   // 基于内容的场景检测
  MotionBased = 'MotionBased',     // 基于运动的场景检测
  ColorBased = 'ColorBased',       // 基于颜色的场景检测
  Combined = 'Combined',           // 组合检测
}

// 场景检测结果
export interface SceneDetectionResult {
  video_path: string;
  scenes: SceneInfo[];
  best_frames: number[];
  detection_method: SceneDetectionMethod;
  confidence_scores: number[];
}

// 缩略图生成选项
export interface ThumbnailGenerationOptions {
  enable_retry: boolean;
  max_retries: number;
  retry_delay_ms: number;
  enable_parallel: boolean;
  max_concurrent: number;
  enable_cache: boolean;
  cache_duration_hours: number;
  enable_validation: boolean;
  min_file_size: number;
}

// 批量缩略图生成请求
export interface BatchThumbnailRequest {
  video_paths: string[];
  config: ThumbnailConfig;
  timeline_config?: TimelineConfig;
}

// 文件夹扫描请求
export interface FolderScanRequest {
  folder_path: string;
  config: ThumbnailConfig;
  timeline_config?: TimelineConfig;
}

// 缩略图预览请求
export interface ThumbnailPreviewRequest {
  video_path: string;
  timestamp: number;
  width: number;
  height: number;
}

// 默认配置
export const DEFAULT_THUMBNAIL_CONFIG: ThumbnailConfig = {
  time_points: [{ Percentage: 0.5 }], // 默认50%位置
  size: {
    width: 320,
    height: 240,
    preset: SizePreset.Small,
  },
  format: ImageFormat.Jpg,
  quality: 85,
  output_dir: 'thumbnails',
  naming_pattern: '{filename}_{timestamp}.{ext}',
  preserve_aspect_ratio: true,
};

export const DEFAULT_TIMELINE_CONFIG: TimelineConfig = {
  frame_count: 10,
  layout: 'Horizontal',
  show_timestamps: true,
  spacing: 2,
  background_color: '#000000',
  border_width: 1,
};

export const DEFAULT_GENERATION_OPTIONS: ThumbnailGenerationOptions = {
  enable_retry: true,
  max_retries: 3,
  retry_delay_ms: 1000,
  enable_parallel: true,
  max_concurrent: 4,
  enable_cache: true,
  cache_duration_hours: 24,
  enable_validation: true,
  min_file_size: 1024, // 1KB
};

// 尺寸预设映射
export const SIZE_PRESET_DIMENSIONS: Record<SizePreset, [number, number]> = {
  [SizePreset.Tiny]: [160, 120],
  [SizePreset.Small]: [320, 240],
  [SizePreset.Medium]: [640, 480],
  [SizePreset.Large]: [1280, 720],
  [SizePreset.FullHD]: [1920, 1080],
  [SizePreset.Custom]: [320, 240], // 默认值
};

// 图片格式扩展名映射
export const IMAGE_FORMAT_EXTENSIONS: Record<ImageFormat, string> = {
  [ImageFormat.Jpg]: 'jpg',
  [ImageFormat.Png]: 'png',
  [ImageFormat.WebP]: 'webp',
};

// 图片格式MIME类型映射
export const IMAGE_FORMAT_MIME_TYPES: Record<ImageFormat, string> = {
  [ImageFormat.Jpg]: 'image/jpeg',
  [ImageFormat.Png]: 'image/png',
  [ImageFormat.WebP]: 'image/webp',
};

// 任务状态显示文本映射
export const TASK_STATUS_LABELS: Record<TaskStatus, string> = {
  [TaskStatus.Pending]: '等待中',
  [TaskStatus.Running]: '执行中',
  [TaskStatus.Completed]: '已完成',
  [TaskStatus.Failed]: '失败',
  [TaskStatus.Cancelled]: '已取消',
  [TaskStatus.Paused]: '已暂停',
};

// 任务状态颜色映射
export const TASK_STATUS_COLORS: Record<TaskStatus, string> = {
  [TaskStatus.Pending]: 'text-yellow-600 bg-yellow-50',
  [TaskStatus.Running]: 'text-blue-600 bg-blue-50',
  [TaskStatus.Completed]: 'text-green-600 bg-green-50',
  [TaskStatus.Failed]: 'text-red-600 bg-red-50',
  [TaskStatus.Cancelled]: 'text-gray-600 bg-gray-50',
  [TaskStatus.Paused]: 'text-orange-600 bg-orange-50',
};

// 工具函数
export const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  
  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`;
};

export const formatFileSize = (bytes: number): string => {
  const units = ['B', 'KB', 'MB', 'GB'];
  let size = bytes;
  let unitIndex = 0;
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`;
};

export const formatProcessingSpeed = (speed: number): string => {
  if (speed < 1) {
    return `${(speed * 60).toFixed(1)} 文件/分钟`;
  }
  return `${speed.toFixed(1)} 文件/秒`;
};
