import _ from "lodash";

import Request from "@/lib/request/Request.ts";
import { generateVideo } from "@/api/controllers/video.ts";
import { tokenSplit } from "@/api/controllers/core.ts";
import util from "@/lib/util.ts";
import { VideoTaskCache } from '@/api/VideoTaskCache.ts';
import databaseService from '@/lib/services/DatabaseGenerationService.js';

// 环境变量控制新旧方法切换
const USE_DATABASE_MODE = process.env.USE_DATABASE_MODE === 'true';

export default {
  prefix: "/v1/video",
  get: {
    "/query": async (request: Request) => {
      request
        .validate("query.task_id", _.isString) // 从 query 中校验
      const {
        task_id,
      } = request.query; // 从 query 中获取
      
      if (USE_DATABASE_MODE) {
        // 使用数据库模式
        return await databaseService.queryTaskResult(task_id);
      } else {
        // 使用原有的内存缓存模式
        const videoTaskCache = VideoTaskCache.getInstance();
        
        // 使用新的方法获取任务结果并清理缓存
        let result = videoTaskCache.getTaskResultAndClear(task_id);
        
        if (result && typeof result.status === 'number' && result.status < 0) {
          // 任务已完成
          return {
            created: util.unixTimestamp(),
            data: { 
              task_id, 
              url: result.url || "", 
              status: result.status,
              error_message: result.errorMessage || null
            },
          };
        } else {
          // 任务进行中或失败，不清理缓存
          result = videoTaskCache.getTaskStatus(task_id);
          return {
            created: util.unixTimestamp(),
            data: { 
              task_id, 
              url: "", 
              status: result?.status || 0,
              error_message: result?.errorMessage || null
            },
          };
        }
      }
    },
  },

  post: {
    "/generations": async (request: Request) => {
      request
        .validate("body.task_id", _.isString)
        .validate("body.prompt", _.isString)
        .validate("body.images", v => _.isUndefined(v) || _.isArray(v))
        .validate("body.is_pro", v => _.isUndefined(v) || _.isBoolean(v))
        .validate("body.duration", v => _.isUndefined(v) || _.isFinite(v))
        .validate("body.ratio", v => _.isUndefined(v) || _.isString(v))
        .validate("headers.authorization", _.isString);
      
      // refresh_token切分
      const tokens = tokenSplit(request.headers.authorization);
      // 随机挑选一个refresh_token
      const token = _.sample(tokens);
      const {
        task_id,
        prompt,
        images,
        is_pro,
        duration,
        ratio,
      } = request.body;
      
      if (USE_DATABASE_MODE) {
        // 使用数据库模式
        await databaseService.generateVideoV2(task_id, prompt, {
          images: images,
          isPro: is_pro,
          duration: duration ? duration * 1000 : undefined,
          ratio,
        }, token);
      } else {
        // 使用原有的内存缓存模式
        // const imageUrls = await generateVideo(model, task_id, prompt, {
        // 不等结果 直接返回
        generateVideo(task_id, prompt, {
          images: images,
          isPro: is_pro,
          duration: duration * 1000,
          ratio,
        }, token);
      }
      
      return {
        created: util.unixTimestamp(),
        data: 'success',
      };
    },
  },
};
