/**
 * Voice 语音 API 模块
 * ===================
 *
 * TTS 合成、批量合成、声音复刻接口封装。
 */

import { invoke } from '@tauri-apps/api/core';
import { client } from '../client';

// ====================== TTS 类型 ======================

export interface VoiceInfo {
  voiceId: string;
  name: string;
  description: string;
  recommended: boolean;
  language?: string;
  previewUrl?: string;
}

interface TTSSynthesizeRequest {
  text: string;
  voiceId?: string;
  speed?: number;
  volume?: number;
  pitch?: number;
}

interface TTSResult {
  audioUrl: string;
  format: string;
  text: string;
  voiceId: string;
  consumedPoints?: number;
  duration?: number;
}

// ====================== 声音复刻类型 ======================

interface VoiceCloneSubmitRequest {
  sourceAudioUrl: string;
  sourceText?: string;
  voiceName?: string;
}

interface VoiceCloneTaskResponse {
  taskId: string;
  status: string;
  voiceId?: string;
  trialUrl?: string;
  errorMessage?: string;
}

// ====================== 素材库类型 ======================

export interface VoiceMaterial {
  id: string;
  name: string;
  voiceId: string;        // Kling 返回的音色 ID
  sourceUrl: string;      // 七牛云原始音频 URL
  trialUrl?: string;      // Kling 试听 URL
  status: 'pending' | 'processing' | 'ready' | 'failed';
  createdAt: string;
}

// ====================== 音频文件管理类型 ======================

export interface AudioMeta {
  id: string;
  name: string;
  filePath: string;
  duration: number;
  fileSize: number;
  voiceId: string;
  createdAt: string;
  segmentId?: string;
}

// ====================== TTS API ======================

/** 获取预设音色列表 */
export async function getVoiceList(): Promise<VoiceInfo[]> {
  const data = await client.get<{ voiceId: string; name: string; description: string; recommended: boolean; previewUrl?: string; language?: string }[]>('/voice/voices');
  return data.map(v => ({
    voiceId: v.voiceId,
    name: v.name,
    description: v.description,
    recommended: v.recommended,
    language: v.language,
    previewUrl: v.previewUrl,
  }));
}

/** 同步 TTS 合成（返回音频 URL） */
export async function synthesizeTTS(request: TTSSynthesizeRequest): Promise<TTSResult> {
  return client.post<TTSResult>('/voice/synthesize', request);
}

/** 上传音频文件到七牛云 */
export async function uploadAudio(file: File): Promise<string> {
  const formData = new FormData();
  formData.append('file', file);
  const result = await client.postForm<{ url: string; key: string }>('/upload/audio', formData);
  return result.url;
}

// ====================== 声音复刻 API ======================

/** 提交声音复刻任务 */
export async function submitCloneTask(request: VoiceCloneSubmitRequest): Promise<VoiceCloneTaskResponse> {
  return client.post<VoiceCloneTaskResponse>('/voice/clone/submit', request);
}

/** 查询克隆任务状态 */
export async function queryCloneTask(taskId: string, blocking = false): Promise<VoiceCloneTaskResponse> {
  return client.get<VoiceCloneTaskResponse>(`/voice/clone/query/${taskId}?blocking=${blocking}`);
}

// ====================== 素材库 API ======================

/** 从本地加载音色素材库 */
export async function loadVoiceMaterials(): Promise<VoiceMaterial[]> {
  const result = await invoke<{ code: number; data?: VoiceMaterial[]; message: string }>('load_voice_materials');
  if (result.code !== 200) {
    throw new Error(result.message || '加载素材库失败');
  }
  return result.data || [];
}

/** 保存音色素材到本地 */
export async function saveVoiceMaterial(material: VoiceMaterial): Promise<void> {
  const result = await invoke<{ code: number; message: string }>('save_voice_material', {
    args: {
      id: material.id,
      name: material.name,
      voiceId: material.voiceId,
      sourceUrl: material.sourceUrl,
      trialUrl: material.trialUrl,
      status: material.status,
      createdAt: material.createdAt,
    },
  });
  if (result.code !== 200) {
    throw new Error(result.message || '保存素材失败');
  }
}

/** 删除本地音色素材 */
export async function deleteVoiceMaterial(materialId: string): Promise<void> {
  const result = await invoke<{ code: number; message: string }>('delete_voice_material_cmd', { id: materialId });
  if (result.code !== 200) {
    throw new Error(result.message || '删除素材失败');
  }
}

// ====================== 本地音频文件管理（Tauri IPC） ======================

/** 保存音频文件到本地 */
export async function saveAudio(args: {
  projectId: string;
  audioId: string;
  audioData: string; // base64 编码
  name: string;
  voiceId: string;
  duration: number;
}): Promise<AudioMeta> {
  const result = await invoke<{ code: number; data?: AudioMeta; message: string }>('save_audio', { args });
  if (result.code !== 200 || !result.data) {
    throw new Error(result.message || '保存音频失败');
  }
  return result.data;
}

// ====================== 音频处理命令（Tauri IPC） ======================

interface ExtractAudioSegmentRequest {
  inputPath: string;
  start: number;
  duration: number;
  outputPath: string;
}

/** 截取音频片段 */
export async function extractAudioSegment(args: ExtractAudioSegmentRequest): Promise<string> {
  const result = await invoke<{ code: number; data?: string; message: string }>('extract_audio_segment', {
    args: {
      inputPath: args.inputPath,
      start: args.start,
      duration: args.duration,
      outputPath: args.outputPath,
    },
  });
  if (result.code !== 200 || !result.data) {
    throw new Error(result.message || '截取音频片段失败');
  }
  return result.data;
}
