// 语音识别 + TTS API
import { request, type ApiResponse } from './client';

interface TranscribeResult {
  success: boolean;
  text: string;
  language: string;
  duration_ms: number;
}

interface STTStatus {
  service: string;
  stt: {
    available: boolean;
    binary_available: boolean;
    model_loaded: boolean;
    binary_path: string;
    model_path: string;
    model_name: string;
    default_language: string;
    supported_languages: string[];
  };
}

interface TTSVoice {
  name: string;
  display_name: string;
  gender: string;
  locale: string;
}

interface TTSSynthesizeRequest {
  text: string;
  voice?: string;
  rate?: string;
}

interface TTSStatus {
  service: string;
  tts: {
    available: boolean;
    edge_tts: boolean;
    espeak_ng: boolean;
    engine: string;
    default_voice: string;
    builtin_voices: number;
  };
}

interface VoiceFullStatus {
  service: string;
  stt: STTStatus['stt'];
  tts: TTSStatus['tts'];
}

/**
 * 音频文件转文字
 * @param audioBlob 音频文件 Blob
 * @param language 语言代码 (zh, en, ja, ko, auto)，默认 zh
 */
async function transcribeAudio(audioBlob: Blob, language?: string): Promise<ApiResponse<TranscribeResult>> {
  const formData = new FormData();
  formData.append('audio', audioBlob, 'audio.wav');
  if (language) {
    formData.append('language', language);
  }

  const token = localStorage.getItem('token');
  const headers: Record<string, string> = {};
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  // 不设置 Content-Type，让浏览器自动处理 multipart boundary

  try {
    const response = await fetch('/api/v1/voice/transcribe', {
      method: 'POST',
      headers,
      body: formData,
    });

    const data = await response.json().catch(() => null);

    if (!response.ok) {
      return {
        error: data?.error || `请求失败 (${response.status})`,
        status: response.status,
      };
    }

    return { data: data as TranscribeResult, status: response.status };
  } catch (err) {
    return {
      error: err instanceof Error ? err.message : '网络错误',
      status: 0,
    };
  }
}

/**
 * 服务端 TTS 合成（返回 audio blob URL）
 * @returns 音频文件的 Object URL
 */
async function synthesizeSpeech(req: TTSSynthesizeRequest): Promise<string> {
  const token = localStorage.getItem('token');
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
  };
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch('/api/v1/voice/tts', {
    method: 'POST',
    headers,
    body: JSON.stringify(req),
  });

  if (!response.ok) {
    const errorData = await response.json().catch(() => null);
    throw new Error(errorData?.error || `TTS 合成失败 (${response.status})`);
  }

  const blob = await response.blob();
  return URL.createObjectURL(blob);
}

/**
 * 获取可用 TTS 语音列表
 */
async function getTTSVoices(): Promise<TTSVoice[]> {
  const response = await request<{ voices: TTSVoice[]; count: number }>('/voice/tts/voices');
  if (response.error) throw new Error(response.error);
  return response.data?.voices ?? [];
}

/**
 * 获取 TTS 服务状态
 */
async function getTTSStatus(): Promise<TTSStatus> {
  const response = await request<TTSStatus>('/voice/tts/status');
  if (response.error) throw new Error(response.error);
  return response.data!;
}

/**
 * 获取 STT 服务状态
 */
async function getSTTStatus(): Promise<ApiResponse<STTStatus>> {
  return request<STTStatus>('/voice/status');
}

/**
 * 获取语音服务完整状态（STT + TTS）
 */
async function getVoiceFullStatus(): Promise<VoiceFullStatus> {
  const response = await request<VoiceFullStatus>('/voice/status');
  if (response.error) throw new Error(response.error);
  return response.data!;
}

export { transcribeAudio, synthesizeSpeech, getSTTStatus, getTTSStatus, getTTSVoices, getVoiceFullStatus };
export type { TranscribeResult, STTStatus, TTSVoice, TTSSynthesizeRequest, TTSStatus, VoiceFullStatus };
