import { Injectable, Logger } from '@nestjs/common';
import { AI3DProvider, AI3DGenerateResult } from './ai-3d-provider.interface';
import { v4 as uuidv4 } from 'uuid';

interface MockTask {
  status: 'pending' | 'processing' | 'completed' | 'failed';
  startTime: number;
  inputType: string;
  inputContent: string;
  resultUrl?: string;
  previewUrl?: string;
  resultUrls?: string[];
  previewUrls?: string[];
  errorMessage?: string;
}

/**
 * Mock AI 3D Provider
 * 用于开发阶段模拟 AI 3D 生成服务
 */
@Injectable()
export class MockAI3DProvider implements AI3DProvider {
  private readonly logger = new Logger(MockAI3DProvider.name);
  private tasks = new Map<string, MockTask>();

  // 模拟完成时间范围（毫秒）
  private readonly MIN_COMPLETION_TIME = 5000; // 5秒
  private readonly MAX_COMPLETION_TIME = 15000; // 15秒

  // 模拟成功率
  private readonly SUCCESS_RATE = 0.9; // 90% 成功率

  // 示例 3D 模型 URL（使用公开可访问的 GLB 文件）
  private readonly SAMPLE_MODELS = [
    // three.js 官方示例模型
    'https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf',
    'https://threejs.org/examples/models/gltf/LittlestTokyo.glb',
    'https://threejs.org/examples/models/gltf/Soldier.glb',
    'https://threejs.org/examples/models/gltf/RobotExpressive/RobotExpressive.glb',
  ];

  // 示例预览图（使用占位图服务）
  private readonly SAMPLE_PREVIEWS = [
    'https://picsum.photos/seed/model1/400/300',
    'https://picsum.photos/seed/model2/400/300',
    'https://picsum.photos/seed/model3/400/300',
    'https://picsum.photos/seed/model4/400/300',
  ];

  async submitTask(
    inputType: 'text' | 'image',
    inputContent: string,
  ): Promise<string> {
    const taskId = uuidv4();

    this.logger.log(
      `Mock: 创建任务 ${taskId}, 类型: ${inputType}, 内容: ${inputContent.substring(0, 50)}...`,
    );

    // 创建任务记录
    this.tasks.set(taskId, {
      status: 'processing',
      startTime: Date.now(),
      inputType,
      inputContent,
    });

    // 模拟异步完成
    const completionTime =
      this.MIN_COMPLETION_TIME +
      Math.random() * (this.MAX_COMPLETION_TIME - this.MIN_COMPLETION_TIME);

    setTimeout(() => {
      this.completeTask(taskId);
    }, completionTime);

    return taskId;
  }

  async queryTask(taskId: string): Promise<AI3DGenerateResult> {
    const task = this.tasks.get(taskId);

    if (!task) {
      this.logger.warn(`Mock: 任务 ${taskId} 不存在`);
      return {
        taskId,
        status: 'failed',
        errorMessage: '任务不存在',
      };
    }

    return {
      taskId,
      status: task.status,
      resultUrl: task.resultUrl,
      previewUrl: task.previewUrl,
      resultUrls: task.resultUrls,
      previewUrls: task.previewUrls,
      errorMessage: task.errorMessage,
    };
  }

  /**
   * 模拟任务完成
   */
  private completeTask(taskId: string): void {
    const task = this.tasks.get(taskId);
    if (!task) return;

    // 根据成功率决定是否成功
    const isSuccess = Math.random() < this.SUCCESS_RATE;

    if (isSuccess) {
      // 文生3D生成4个不同角度的模型
      if (task.inputType === 'text') {
        const resultUrls: string[] = [];
        const previewUrls: string[] = [];

        // 生成4个模型结果，使用不同的示例模型
        for (let i = 0; i < 4; i++) {
          const modelIndex = i % this.SAMPLE_MODELS.length;
          const previewIndex = i % this.SAMPLE_PREVIEWS.length;
          resultUrls.push(this.SAMPLE_MODELS[modelIndex]);
          previewUrls.push(this.SAMPLE_PREVIEWS[previewIndex]);
        }

        task.status = 'completed';
        task.resultUrls = resultUrls;
        task.previewUrls = previewUrls;
        // 兼容旧字段，使用第一个结果
        task.resultUrl = resultUrls[0];
        task.previewUrl = previewUrls[0];

        this.logger.log(
          `Mock: 文生3D任务 ${taskId} 完成, 生成 ${resultUrls.length} 个模型`,
        );
      } else {
        // 图生3D只生成1个模型
        const modelIndex = Math.floor(
          Math.random() * this.SAMPLE_MODELS.length,
        );
        const modelUrl = this.SAMPLE_MODELS[modelIndex];
        const previewUrl = this.SAMPLE_PREVIEWS[modelIndex % this.SAMPLE_PREVIEWS.length];

        task.status = 'completed';
        task.resultUrl = modelUrl;
        task.previewUrl = previewUrl;
        task.resultUrls = [modelUrl];
        task.previewUrls = [previewUrl];

        this.logger.log(`Mock: 图生3D任务 ${taskId} 完成, 模型: ${modelUrl}`);
      }
    } else {
      task.status = 'failed';
      task.errorMessage = '模拟生成失败：AI 服务暂时不可用';

      this.logger.warn(`Mock: 任务 ${taskId} 失败`);
    }

    this.tasks.set(taskId, task);

    // 清理过期任务（保留1小时）
    this.cleanupOldTasks();
  }

  /**
   * 清理超过1小时的任务记录
   */
  private cleanupOldTasks(): void {
    const oneHourAgo = Date.now() - 60 * 60 * 1000;

    for (const [taskId, task] of this.tasks.entries()) {
      if (task.startTime < oneHourAgo) {
        this.tasks.delete(taskId);
        this.logger.debug(`Mock: 清理过期任务 ${taskId}`);
      }
    }
  }
}
