/**
 * Topaz Video AI 模板服务
 * 负责从后端获取模板数据
 */

export interface TopazSettings {
  stabilize: {
    active: boolean;
    smooth: number;
    method: number;
    rsc: boolean;
    reduce_motion: boolean;
    reduce_motion_iteration: number;
  };
  motionblur: {
    active: boolean;
    model: string;
    model_name?: string;
  };
  slowmo: {
    active: boolean;
    model: string;
    factor: number;
    duplicate: boolean;
    duplicate_threshold: number;
  };
  enhance: {
    active: boolean;
    model: string;
    video_type: number;
    auto: number;
    field_order: number;
    compress: number;
    detail: number;
    sharpen: number;
    denoise: number;
    dehalo: number;
    deblur: number;
    add_noise: number;
    recover_original_detail_value: number;
    focus_fix_level?: string;
    is_artemis: boolean;
    is_gaia: boolean;
    is_theia: boolean;
    is_proteus: boolean;
    is_iris: boolean;
    is_second_enhancement?: boolean;
  };
  grain: {
    active: boolean;
    grain: number;
    grain_size: number;
  };
  output: {
    active: boolean;
    out_size_method: number;
    crop_to_fit: boolean;
    output_par: number;
    out_fps: number;
    lock_aspect_ratio: boolean;
  };
  hdr?: {
    active: boolean;
    model: string;
    auto: number;
    exposure: number;
    saturation: number;
    sdr_inflection_point: number;
  };
}

export interface TemplateInfo {
  name: string;
  description: string;
  category?: string;
  icon?: string;
  settings: TopazSettings;
}

/**
 * 从后端获取模板列表
 */
export const fetchTopazTemplates = async (): Promise<Record<string, TemplateInfo>> => {
  try {
    // 使用 Tauri command 调用后端
    const { invoke } = await import('@tauri-apps/api/core');
    const templates = await invoke('get_topaz_templates');
    return templates as Record<string, TemplateInfo>;
  } catch (error) {
    console.warn('无法从 Tauri 后端获取模板，使用默认模板:', error);
    return {};
  }
};

/**
 * 生成 FFmpeg 命令
 */
export const generateFFmpegCommand = async (
  settings: TopazSettings,
  inputFile: string,
  outputFile: string,
  processingMode: string,
  rateControl: string
): Promise<{ success: boolean; command?: string; error?: string }> => {
  try {
    // 使用 Tauri command 调用后端
    const { invoke } = await import('@tauri-apps/api/core');
    const result = await invoke('generate_topaz_command', {
      settings,
      inputFile,
      outputFile,
      processingMode,
      rateControl,
    });
    return { success: true, command: result as string };
  } catch (error) {
    console.error('生成命令失败:', error);
    return { success: false, error: String(error) };
  }
};
