/**
 * BowongTextVideoAgent API 类型定义
 * 基于 OpenAPI 规范生成的完整类型定义
 * 版本: 1.0.6
 */

// ============================================================================
// 基础类型定义
// ============================================================================

/**
 * HTTP 验证错误详情
 */
export interface ValidationError {
  loc: (string | number)[];
  msg: string;
  type: string;
}

/**
 * HTTP 验证错误响应
 */
export interface HTTPValidationError {
  detail: ValidationError[];
}

/**
 * 通用 API 响应格式
 */
export interface ApiResponse<T = any> {
  status: boolean;
  msg: string;
  data?: T;
}

/**
 * 文件上传响应
 */
export interface FileUploadResponse {
  status: boolean;
  msg: string;
  data: string | null; // 文件URL
}

/**
 * 任务状态枚举
 */
export enum TaskStatus {
  PENDING = 'pending',
  RUNNING = 'running',
  SUCCESS = 'success',
  FAILED = 'failed',
  CANCELLED = 'cancelled'
}

/**
 * 媒体源
 */
export interface MediaSource {
  urn: string;
  content_length: number;
  metadata: VideoMetadata;
  url: string;
}

/**
 * 视频元数据
 */
export interface VideoMetadata {
  streams: (VideoStream | AudioStream | ImageStream | SubtitleStream)[];
  format?: VideoFormat | null;
}

/**
 * 视频流信息
 */
export interface VideoStream {
  duration: number;
  codec_name: string;
  width: number;
  height: number;
  fps: number;
  stream_type: 'video';
}

/**
 * 音频流信息
 */
export interface AudioStream {
  duration: number;
  codec_name: string;
  sample_rate: number;
  channels: number;
  stream_type: 'audio';
}

/**
 * 图片流信息
 */
export interface ImageStream {
  duration: number;
  codec_name: string;
  width: number;
  height: number;
  stream_type: 'image';
}

/**
 * 字幕流信息
 */
export interface SubtitleStream {
  codec_name: string;
  tags: SubtitleStreamTags;
  stream_type: 'subtitle';
}

/**
 * 字幕流标签
 */
export interface SubtitleStreamTags {
  language: string;
}

/**
 * 视频格式信息
 */
export interface VideoFormat {
  format_name: string;
  duration: number;
  size: number;
  bit_rate: number;
}

// ============================================================================
// 提示词预处理模块
// ============================================================================

/**
 * 获取示例提示词请求参数
 */
export interface GetSamplePromptParams {
  task_type?: string | null;
}

/**
 * 示例提示词响应
 */
export interface SamplePromptResponse {
  [key: string]: any;
}

// ============================================================================
// 文件操作模块
// ============================================================================

/**
 * 文件上传请求
 */
export interface FileUploadRequest {
  file: File;
}

/**
 * S3文件上传请求
 */
export interface S3FileUploadRequest {
  file: File;
}

// ============================================================================
// 视频模板管理模块
// ============================================================================

/**
 * 视频模板
 */
export interface VideoTemplate {
  id?: string;
  prompt: string;
  cover_url: string;
  video_url: string;
  description: string;
  detailDescription: string;
  title_zh: string;
  aspect_ratio: string;
  engine: string;
  presetPrompts: string;
  task_type: string;
  created_at?: string;
  updated_at?: string;
}

/**
 * 获取模板列表请求参数
 */
export interface GetTemplatesParams {
  task_type?: string | null;
  page?: number;
  page_size?: number;
}

/**
 * 模板列表响应
 */
export interface TemplateListResponse {
  status: boolean;
  data: VideoTemplate[];
  page: number;
  page_size: number;
  total: number;
  total_pages: number;
}

/**
 * 检查任务类型请求参数
 */
export interface CheckTaskTypeParams {
  task_type: string;
}

/**
 * 创建模板请求
 */
export interface CreateTemplateRequest extends Omit<VideoTemplate, 'id' | 'created_at' | 'updated_at'> {}

/**
 * 更新模板请求
 */
export interface UpdateTemplateRequest extends VideoTemplate {
  id: string;
}

// ============================================================================
// 任务管理模块
// ============================================================================

/**
 * 任务请求
 */
export interface TaskRequest {
  task_type?: string | null;
  prompt: string;
  img_url?: string | null;
  ar?: string; // 默认 "9:16"
}

/**
 * 视频请求
 */
export interface VideoRequest {
  prompt: string;
}

/**
 * 任务响应
 */
export interface TaskResponse {
  status: boolean;
  data: string; // 任务ID存储在这里
  msg: string;
}

/**
 * 任务状态查询响应
 */
export interface TaskStatusResponse {
  task_id: string;
  status: TaskStatus;
  progress?: number;
  result?: any;
  error?: string;
  created_at?: string;
  updated_at?: string;
}

// ============================================================================
// Midjourney 图片生成模块
// ============================================================================

/**
 * 提示词检查请求参数
 */
export interface PromptCheckParams {
  prompt: string;
}

/**
 * 同步生成图片请求
 */
export interface SyncImageGenerationRequest {
  prompt: string;
  img_file?: File;
  max_wait_time?: number; // 默认 120
  poll_interval?: number; // 默认 2
}

/**
 * 异步生成图片请求
 */
export interface AsyncImageGenerationRequest {
  prompt: string;
  img_file?: File;
}

/**
 * 图片描述请求
 */
export interface ImageDescribeRequest {
  image_url?: string;
  img_file?: File;
  max_wait_time?: number; // 默认 120
  poll_interval?: number; // 默认 2
}

/**
 * 图片生成响应
 */
export interface ImageGenerationResponse {
  task_id: string;
  status: TaskStatus;
  images?: string[];
  error?: string;
}

// ============================================================================
// 极梦视频生成模块
// ============================================================================

/**
 * 视频生成请求
 */
export interface VideoGenerationRequest {
  prompt: string;
  img_url?: string;
  img_file?: File;
  duration?: number; // 默认 5
  max_wait_time?: number; // 默认 300
  poll_interval?: number; // 默认 5
  model_type?: 'lite' | 'pro'; // 默认 'lite'
}

/**
 * 视频生成响应
 */
export interface VideoGenerationResponse {
  task_id: string;
  status: TaskStatus;
  video_url?: string;
  progress?: number;
  error?: string;
}

/**
 * 视频任务状态
 */
export interface VideoTaskStatus {
  job_ids: string[];
}

/**
 * 批量视频状态响应
 */
export interface BatchVideoStatusResponse {
  data: {
    finished: Array<{ job_id: string; video_url: string }>;
    failed: string[];
    running: string[];
  };
  status: boolean;
  msg: string;
}

// ============================================================================
// 302AI 服务集成模块
// ============================================================================

/**
 * 302AI Midjourney 图片生成请求
 */
export interface AI302MJImageRequest {
  prompt: string;
  img_file?: File;
}

/**
 * 302AI 任务取消请求
 */
export interface AI302TaskCancelRequest {
  task_id: string;
}

/**
 * 302AI 任务状态查询参数
 */
export interface AI302TaskStatusParams {
  task_id: string;
  task_type?: 'image' | 'describe'; // 默认 'image'
}

/**
 * 302AI 极梦视频生成请求
 */
export interface AI302JMVideoRequest {
  prompt: string;
  img_url?: string;
  img_file?: File;
  duration?: number; // 默认 5
  max_wait_time?: number; // 默认 300
  poll_interval?: number; // 默认 5
  model_type?: 'lite' | 'pro'; // 默认 'lite'
}

/**
 * 302AI VEO视频生成请求
 */
export interface AI302VEOVideoRequest {
  prompt: string;
  img_file?: File;
  max_wait_time?: number; // 默认 500
  interval?: number; // 默认 5
}

/**
 * 302AI VEO任务状态查询参数
 */
export interface AI302VEOTaskStatusParams {
  task_id: string;
  img_mode?: boolean; // 默认 false
}

// ============================================================================
// 海螺API模块
// ============================================================================

/**
 * 语音合成请求
 */
export interface SpeechGenerationRequest {
  text: string;
  voice_id: string;
  speed?: number; // [0.5, 2] 默认 1.0
  vol?: number; // (0, 10] 默认 1.0
  emotion?: 'happy' | 'sad' | 'angry' | 'fearful' | 'disgusted' | 'surprised' | 'calm';
}

/**
 * 音频文件上传请求
 */
export interface AudioFileUploadRequest {
  audio_file: File;
  purpose?: string; // 默认 'voice_clone'
}

/**
 * 声音克隆请求
 */
export interface VoiceCloneRequest {
  text: string;
  model?: 'speech-02-hd' | 'speech-02-turbo' | 'speech-01-hd' | 'speech-01-turbo'; // 默认 'speech-02-hd'
  need_noise_reduction?: boolean; // 默认 true
  voice_id?: string;
  prefix?: string; // 默认 'BoWong-'
  audio_file?: File;
}

/**
 * 音色列表响应
 */
export interface VoiceListResponse {
  voices: Array<{
    voice_id: string;
    name: string;
    description?: string;
  }>;
}

// ============================================================================
// 聚合接口模块
// ============================================================================

/**
 * 模型列表响应
 */
export interface ModelListResponse {
  models: string[];
}

/**
 * 聚合图片生成请求
 */
export interface UnionImageGenerationRequest {
  model?: string; // 默认 'midjourney-v7-t2i'
  prompt: string;
  img_file: File;
  aspect_ratio?: string; // 默认 '9:16'
}

/**
 * 聚合视频生成请求
 */
export interface UnionVideoGenerationRequest {
  prompt: string;
  img_file: File;
  model?: string; // 默认 'seedance_i2v'
  duration?: number; // 默认 5
}

// ============================================================================
// ComfyUI 工作流模块
// ============================================================================

/**
 * 获取运行节点请求参数
 */
export interface GetRunningNodeParams {
  task_count?: number; // 默认 1
}

/**
 * ComfyUI 任务提交请求
 */
export interface ComfyUITaskRequest {
  prompt: string; // 工作流节点数据
}

/**
 * ComfyUI 任务状态查询参数
 */
export interface ComfyUITaskStatusParams {
  task_id: string;
}

/**
 * ComfyUI 同步执行请求
 */
export interface ComfyUISyncExecuteRequest {
  prompt: string; // 工作流JSON字符串
}

// ============================================================================
// Hedra 口型合成模块
// ============================================================================

/**
 * Hedra 文件上传请求
 */
export interface HedraFileUploadRequest {
  file_path: string;
  purpose?: 'image' | 'audio' | 'video' | 'voice'; // 默认 'image'
}

/**
 * Hedra 任务提交请求
 */
export interface HedraTaskSubmitRequest {
  audio_file: string;
  img_file: string;
  prompt?: string;
  resolution?: '720p' | '540p';
  aspect_ratio?: '1:1' | '16:9' | '9:16';
  params?: Record<string, any>;
}

/**
 * Hedra 任务状态查询参数
 */
export interface HedraTaskStatusParams {
  task_id: string;
}

// ============================================================================
// FFMPEG 任务模块
// ============================================================================

/**
 * FFMPEG 任务状态响应
 */
export interface BaseFFMPEGTaskStatusResponse {
  taskid: string;
  status: TaskStatus;
  error?: string | null;
  code?: number | null;
  results?: (FFMPEGResult | any)[] | null;
  result?: string;
}

/**
 * FFMPEG 结果
 */
export interface FFMPEGResult {
  urn: string;
  content_length: number;
  metadata: VideoMetadata;
  url: string;
}

/**
 * Modal 任务响应
 */
export interface ModalTaskResponse {
  task_id: string;
  status: string;
}

/**
 * Webhook 通知
 */
export interface WebhookNotify {
  url: string;
  method: 'GET' | 'POST';
  headers?: Record<string, string> | null;
}

/**
 * FFMPEG 切片请求
 */
export interface FFMPEGSliceRequest {
  webhook?: WebhookNotify | null;
  media: MediaSource;
  markers: FFMpegSliceSegment[];
  options: FFMPEGSliceOptions;
}

/**
 * FFMPEG 切片段
 */
export interface FFMpegSliceSegment {
  start: number;
  end: number;
  name?: string;
}

/**
 * FFMPEG 切片选项
 */
export interface FFMPEGSliceOptions {
  crf?: number; // 默认 16
  fps?: number; // 默认 30
}

// ============================================================================
// 服务接口定义
// ============================================================================

/**
 * BowongTextVideoAgent FastAPI 服务接口
 */
export interface BowongTextVideoAgentAPI {
  // 提示词预处理
  getSamplePrompt(params?: GetSamplePromptParams): Promise<SamplePromptResponse>;
  checkPromptHealth(): Promise<ApiResponse>;

  // 文件操作
  uploadFile(request: FileUploadRequest): Promise<FileUploadResponse>;
  uploadFileToS3(request: S3FileUploadRequest): Promise<FileUploadResponse>;
  checkFileHealth(): Promise<ApiResponse>;

  // 视频模板管理
  getTemplates(params?: GetTemplatesParams): Promise<TemplateListResponse>;
  checkTaskType(params: CheckTaskTypeParams): Promise<ApiResponse>;
  createTemplate(request: CreateTemplateRequest): Promise<ApiResponse<VideoTemplate>>;
  updateTemplate(request: UpdateTemplateRequest): Promise<ApiResponse<VideoTemplate>>;
  deleteTemplate(templateId: string): Promise<ApiResponse>;

  // Midjourney 图片生成
  checkPrompt(params: PromptCheckParams): Promise<ApiResponse>;
  syncGenerateImage(request: SyncImageGenerationRequest): Promise<ImageGenerationResponse>;
  asyncGenerateImage(request: AsyncImageGenerationRequest): Promise<TaskResponse>;
  queryImageTaskStatus(taskId: string): Promise<TaskStatusResponse>;
  describeImage(request: ImageDescribeRequest): Promise<ApiResponse>;

  // 极梦视频生成
  generateVideo(request: VideoGenerationRequest): Promise<VideoGenerationResponse>;
  syncGenerateVideo(request: VideoGenerationRequest): Promise<VideoGenerationResponse>;
  asyncGenerateVideo(request: VideoGenerationRequest): Promise<TaskResponse>;
  queryVideoTaskStatus(taskId: string): Promise<TaskStatusResponse>;
  batchQueryVideoStatus(request: VideoTaskStatus): Promise<BatchVideoStatusResponse>;

  // 任务管理
  createTask(request: TaskRequest): Promise<TaskResponse>;
  createTaskV2(request: TaskRequest): Promise<TaskResponse>;
  getTaskStatus(taskId: string): Promise<TaskStatusResponse>;

  // 302AI 服务集成
  ai302MJAsyncGenerateImage(request: AI302MJImageRequest): Promise<TaskResponse>;
  ai302MJCancelTask(request: AI302TaskCancelRequest): Promise<ApiResponse>;
  ai302MJQueryTaskStatus(params: AI302TaskStatusParams): Promise<TaskStatusResponse>;
  ai302MJDescribeImage(request: ImageDescribeRequest): Promise<ApiResponse>;
  ai302MJSyncGenerateImage(request: SyncImageGenerationRequest): Promise<ImageGenerationResponse>;

  ai302JMSyncGenerateVideo(request: AI302JMVideoRequest): Promise<VideoGenerationResponse>;
  ai302JMAsyncGenerateVideo(request: AI302JMVideoRequest): Promise<TaskResponse>;
  ai302JMQueryVideoStatus(taskId: string): Promise<TaskStatusResponse>;

  ai302VEOAsyncSubmit(request: AI302VEOVideoRequest): Promise<TaskResponse>;
  ai302VEOSyncGenerateVideo(request: AI302VEOVideoRequest): Promise<VideoGenerationResponse>;
  ai302VEOGetTaskStatus(params: AI302VEOTaskStatusParams): Promise<TaskStatusResponse>;

  // 海螺API
  generateSpeech(request: SpeechGenerationRequest): Promise<ApiResponse>;
  getVoices(): Promise<VoiceListResponse>;
  uploadAudioFile(request: AudioFileUploadRequest): Promise<FileUploadResponse>;
  cloneVoice(request: VoiceCloneRequest): Promise<ApiResponse>;

  // 聚合接口
  getImageModelList(): Promise<ModelListResponse>;
  unionSyncGenerateImage(request: UnionImageGenerationRequest): Promise<ImageGenerationResponse>;
  getVideoModelList(): Promise<ModelListResponse>;
  unionAsyncGenerateVideo(request: UnionVideoGenerationRequest): Promise<TaskResponse>;
  unionQueryVideoTaskStatus(taskId: string): Promise<TaskStatusResponse>;

  // ComfyUI 工作流
  getRunningNode(params?: GetRunningNodeParams): Promise<ApiResponse>;
  submitComfyUITask(request: ComfyUITaskRequest): Promise<TaskResponse>;
  queryComfyUITaskStatus(params: ComfyUITaskStatusParams): Promise<TaskStatusResponse>;
  syncExecuteWorkflow(request: ComfyUISyncExecuteRequest): Promise<ApiResponse>;

  // Hedra 口型合成
  hedraUploadFile(request: HedraFileUploadRequest): Promise<FileUploadResponse>;
  hedraSubmitTask(request: HedraTaskSubmitRequest): Promise<TaskResponse>;
  hedraQueryTaskStatus(params: HedraTaskStatusParams): Promise<TaskStatusResponse>;

  // FFMPEG 任务
  getFFMPEGTaskStatus(taskId: string): Promise<BaseFFMPEGTaskStatusResponse>;
  sliceMedia(request: FFMPEGSliceRequest): Promise<ModalTaskResponse>;
}

/**
 * 服务配置
 */
export interface BowongTextVideoAgentConfig {
  baseUrl: string;
  apiKey?: string;
  timeout?: number;
  retryAttempts?: number;
  retryDelay?: number;
}

/**
 * 错误类型
 */
export class BowongTextVideoAgentError extends Error {
  constructor(
    message: string,
    public code?: string,
    public statusCode?: number,
    public details?: any
  ) {
    super(message);
    this.name = 'BowongTextVideoAgentError';
  }
}

/**
 * 网络错误
 */
export class NetworkError extends BowongTextVideoAgentError {
  constructor(message: string, statusCode?: number) {
    super(message, 'NETWORK_ERROR', statusCode);
    this.name = 'NetworkError';
  }
}

/**
 * 验证错误
 */
export class ValidationError extends BowongTextVideoAgentError {
  constructor(message: string, details?: HTTPValidationError) {
    super(message, 'VALIDATION_ERROR', 422, details);
    this.name = 'ValidationError';
  }
}

/**
 * 任务超时错误
 */
export class TaskTimeoutError extends BowongTextVideoAgentError {
  constructor(message: string, taskId?: string) {
    super(message, 'TASK_TIMEOUT', undefined, { taskId });
    this.name = 'TaskTimeoutError';
  }
}

/**
 * 任务失败错误
 */
export class TaskFailedError extends BowongTextVideoAgentError {
  constructor(message: string, taskId?: string, details?: any) {
    super(message, 'TASK_FAILED', undefined, { taskId, ...details });
    this.name = 'TaskFailedError';
  }
}
