import { DataFlow, NodeType, ProcessingStatus } from '../types/canvas';

interface ProcessingCallbacks {
  onProgress?: (progress: number) => void;
  onComplete?: (result: any) => void;
  onError?: (error: string) => void;
}

/**
 * 异步处理引擎 - 负责管理节点的异步处理任务
 */
export class ProcessingEngine {
  private activeProcesses = new Map<string, AbortController>();
  private processingCallbacks = new Map<string, ProcessingCallbacks>();

  /**
   * 处理单个节点
   */
  async processNode(
    nodeId: string,
    nodeType: NodeType,
    inputData: DataFlow,
    callbacks: ProcessingCallbacks = {}
  ): Promise<DataFlow> {
    // 创建取消控制器
    const controller = new AbortController();
    this.activeProcesses.set(nodeId, controller);
    this.processingCallbacks.set(nodeId, callbacks);

    try {
      // 根据数据类型选择处理方式
      if (inputData.type === 'batch') {
        return await this.processBatch(nodeId, nodeType, inputData, controller.signal);
      } else {
        return await this.processSingle(nodeId, nodeType, inputData, controller.signal);
      }
    } finally {
      // 清理资源
      this.activeProcesses.delete(nodeId);
      this.processingCallbacks.delete(nodeId);
    }
  }

  /**
   * 处理单个数据项
   */
  private async processSingle(
    nodeId: string,
    nodeType: NodeType,
    inputData: DataFlow,
    signal: AbortSignal
  ): Promise<DataFlow> {
    const callbacks = this.processingCallbacks.get(nodeId);

    try {
      let result: any;

      switch (nodeType) {
        case 'promptOptimize':
          result = await this.processPromptOptimize(inputData.content, signal, callbacks?.onProgress);
          break;
        case 'imageGenerate':
          result = await this.processImageGenerate(inputData.content, signal, callbacks?.onProgress);
          break;
        case 'imageEdit':
          result = await this.processImageEdit(inputData.content, signal, callbacks?.onProgress);
          break;
        case 'videoGenerate':
          result = await this.processVideoGenerate(inputData.content, signal, callbacks?.onProgress);
          break;
        default:
          throw new Error(`Unsupported node type: ${nodeType}`);
      }

      const resultData: DataFlow = {
        type: 'single',
        dataType: this.getOutputDataType(nodeType),
        content: result,
        metadata: {
          timestamp: Date.now()
        }
      };

      callbacks?.onComplete?.(result);
      return resultData;

    } catch (error) {
      if (signal.aborted) {
        throw new Error('Processing cancelled');
      }
      const errorMessage = error instanceof Error ? error.message : 'Processing failed';
      callbacks?.onError?.(errorMessage);
      throw error;
    }
  }

  /**
   * 处理批量数据
   */
  private async processBatch(
    nodeId: string,
    nodeType: NodeType,
    batchData: DataFlow,
    signal: AbortSignal
  ): Promise<DataFlow> {
    const callbacks = this.processingCallbacks.get(nodeId);
    const items = batchData.content;
    const results = [];
    const total = items.length;

    for (let i = 0; i < total; i++) {
      if (signal.aborted) {
        throw new Error('Batch processing cancelled');
      }

      try {
        // 更新整体进度
        const overallProgress = (i / total) * 100;
        callbacks?.onProgress?.(overallProgress);

        // 处理单个项目
        const itemData: DataFlow = {
          type: 'single',
          dataType: batchData.dataType,
          content: items[i]
        };

        const result = await this.processSingle(nodeId, nodeType, itemData, signal);
        results.push({
          id: `item-${i}`,
          filename: items[i].filename || `Item ${i + 1}`,
          status: 'success' as ProcessingStatus,
          result: result.content,
          thumbnail: this.generateThumbnail(result.content, this.getOutputDataType(nodeType))
        });

      } catch (error) {
        results.push({
          id: `item-${i}`,
          filename: items[i].filename || `Item ${i + 1}`,
          status: 'error' as ProcessingStatus,
          error: error instanceof Error ? error.message : 'Processing failed'
        });
      }
    }

    // 完成进度
    callbacks?.onProgress?.(100);

    return {
      type: 'batch',
      dataType: this.getOutputDataType(nodeType),
      content: results,
      metadata: {
        totalItems: total,
        completedItems: results.filter(r => r.status === 'success').length,
        failedItems: results.filter(r => r.status === 'error').length,
        timestamp: Date.now()
      }
    };
  }

  /**
   * 取消处理
   */
  cancelProcessing(nodeId: string): void {
    const controller = this.activeProcesses.get(nodeId);
    if (controller) {
      controller.abort();
      this.activeProcesses.delete(nodeId);
      this.processingCallbacks.delete(nodeId);
    }
  }

  /**
   * 检查是否正在处理
   */
  isProcessing(nodeId: string): boolean {
    return this.activeProcesses.has(nodeId);
  }

  /**
   * 获取所有正在处理的节点
   */
  getActiveProcesses(): string[] {
    return Array.from(this.activeProcesses.keys());
  }

  /**
   * 提示词优化处理
   */
  private async processPromptOptimize(
    prompt: string,
    signal: AbortSignal,
    onProgress?: (progress: number) => void
  ): Promise<string> {
    // 模拟AI处理延迟和进度
    for (let i = 0; i <= 100; i += 10) {
      if (signal.aborted) throw new Error('Processing cancelled');
      onProgress?.(i);
      await new Promise(resolve => setTimeout(resolve, 200));
    }

    // 模拟优化结果
    const optimizedPrompt = `优化后的提示词: ${prompt}，添加了更多细节描述，包括光线、构图、风格等元素，使其更适合AI图像生成。`;
    return optimizedPrompt;
  }

  /**
   * 图片生成处理
   */
  private async processImageGenerate(
    prompt: string,
    signal: AbortSignal,
    onProgress?: (progress: number) => void
  ): Promise<string> {
    // 模拟图片生成过程
    for (let i = 0; i <= 100; i += 5) {
      if (signal.aborted) throw new Error('Processing cancelled');
      onProgress?.(i);
      await new Promise(resolve => setTimeout(resolve, 300));
    }

    // 模拟生成的图片URL
    const mockImageUrl = `https://picsum.photos/512/512?random=${Date.now()}`;
    return mockImageUrl;
  }

  /**
   * 图片编辑处理
   */
  private async processImageEdit(
    imageData: any,
    signal: AbortSignal,
    onProgress?: (progress: number) => void
  ): Promise<string> {
    // 模拟图片编辑过程
    for (let i = 0; i <= 100; i += 8) {
      if (signal.aborted) throw new Error('Processing cancelled');
      onProgress?.(i);
      await new Promise(resolve => setTimeout(resolve, 250));
    }

    // 模拟编辑后的图片URL
    const editedImageUrl = `https://picsum.photos/512/512?random=${Date.now()}&edit=true`;
    return editedImageUrl;
  }

  /**
   * 视频生成处理
   */
  private async processVideoGenerate(
    imageData: any,
    signal: AbortSignal,
    onProgress?: (progress: number) => void
  ): Promise<string> {
    // 模拟视频生成过程（较长时间）
    for (let i = 0; i <= 100; i += 2) {
      if (signal.aborted) throw new Error('Processing cancelled');
      onProgress?.(i);
      await new Promise(resolve => setTimeout(resolve, 500));
    }

    // 模拟生成的视频URL
    const mockVideoUrl = `https://sample-videos.com/zip/10/mp4/SampleVideo_360x240_1mb.mp4?t=${Date.now()}`;
    return mockVideoUrl;
  }

  /**
   * 获取输出数据类型
   */
  private getOutputDataType(nodeType: NodeType): 'text' | 'image' | 'video' | 'batch' {
    switch (nodeType) {
      case 'promptOptimize':
        return 'text';
      case 'imageGenerate':
      case 'imageEdit':
        return 'image';
      case 'videoGenerate':
        return 'video';
      default:
        return 'text';
    }
  }

  /**
   * 生成缩略图
   */
  private generateThumbnail(content: any, dataType: string): string | undefined {
    if (dataType === 'image' && typeof content === 'string') {
      return content; // 图片URL直接作为缩略图
    }
    if (dataType === 'video' && typeof content === 'string') {
      // 为视频生成缩略图（这里简化处理）
      return `https://picsum.photos/200/150?random=${Date.now()}`;
    }
    return undefined;
  }
}
