import type { WebGenerationPreviewTask } from "../types";
import { aiGenerationClient } from "./aiGenerationClient";
import { resolveVideoRequestModel } from "../utils/resolveVideoModel";
import { ENTERPRISE_DEFAULT_VIDEO_MODEL } from "../utils/enterpriseVideoPolicy";

function formatPreviewTaskTimestamp(date = new Date()): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}

export interface CreatePreviewTaskInput {
  title: string;
  type: WebGenerationPreviewTask["type"];
  prompt: string;
  params?: {
    existingTaskId?: string;
    projectId?: string;
    conversationId?: number;
    model?: string;
    ratio?: string;
    quality?: string;
    resolution?: string;
    gridMode?: string;
    duration?: number;
    frameMode?: string;
    referenceUrls?: string[];
    audioUrl?: string;
    muted?: boolean;
    hasReferenceVideo?: boolean;
  };
}

export const webGenerationGateway = {
  async createPreviewTask(input: CreatePreviewTaskInput): Promise<WebGenerationPreviewTask> {
    const { type, params } = input;
    const prompt = input.prompt.trim();
    const title = input.title.trim() || "未命名任务";
    const createdAt = formatPreviewTaskTimestamp();

    try {
      let taskId: string;

      if (params?.existingTaskId) {
        taskId = params.existingTaskId;
      } else if (type === "image") {
        const result = await aiGenerationClient.createImageTask({
          projectId: params?.projectId,
          conversationId: params?.conversationId,
          model: params?.model || "nano-banana-pro",
          prompt,
          ratio: params?.ratio || "16:9",
          quality: params?.quality || "1K",
          gridMode: params?.gridMode || "single",
          referenceUrls: params?.referenceUrls,
        });
        taskId = result.taskId;
      } else if (type === "video") {
        const refs = params?.referenceUrls;
        let model: string = params?.model || ENTERPRISE_DEFAULT_VIDEO_MODEL;
        model = resolveVideoRequestModel({ model, referenceUrls: refs });
        const result = await aiGenerationClient.createVideoTask({
          projectId: params?.projectId,
          conversationId: params?.conversationId,
          model,
          prompt,
          ratio: params?.ratio || "16:9",
          duration: params?.duration || 5,
          quality: params?.quality || params?.resolution || "1080P",
          resolution: params?.resolution || params?.quality || "1080P",
          frameMode: params?.frameMode || "start-end",
          referenceUrls: params?.referenceUrls,
          audioUrl: params?.audioUrl,
          muted: params?.muted ?? false,
          hasReferenceVideo: params?.hasReferenceVideo ?? false,
        });
        taskId = result.taskId;
      } else {
        taskId = `web-task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
      }

      return {
        id: taskId,
        title,
        type,
        status: "queued",
        progress: 5,
        prompt,
        createdAt,
        source: "server",
        projectId: params?.projectId,
      };
    } catch (err) {
      return {
        id: `web-task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
        title,
        type,
        status: "failed",
        progress: 0,
        prompt,
        createdAt,
        source: "server",
        errorMessage: err instanceof Error ? err.message : "请求失败，请稍后重试",
      };
    }
  },
};
