import { assetClient } from "../../api/assetClient";
import type { WebAssetItem } from "../../types";
import { saveAssetToLocalLibrary } from "../assets/localAssetStore";
import { downloadResultAsset } from "./workbenchDownload";

export interface ToolResultAssetInput {
  url: string;
  name: string;
  description?: string;
  type: WebAssetItem["type"];
  isVideo?: boolean;
  taskId?: string;
  tags?: string[];
  metadata?: Record<string, unknown>;
}

export async function saveToolResultToLocal(input: ToolResultAssetInput) {
  return downloadResultAsset(input.url, input.name, Boolean(input.isVideo), input.taskId);
}

export async function addToolResultToAssetLibrary(input: ToolResultAssetInput): Promise<"server" | "local"> {
  const description = input.description || "从工具盒生成结果加入的素材。";
  const tags = input.tags?.length ? input.tags : ["工具盒", input.isVideo ? "生成视频" : "生成图片"];

  saveAssetToLocalLibrary({
    type: input.type,
    name: input.name,
    description,
    url: input.url,
    imageUrl: input.url,
    tags,
  });

  try {
    await assetClient.create({
      type: input.type,
      name: input.name,
      description,
      url: input.url,
      imageUrl: input.url,
      tags,
      sourceTaskId: input.taskId,
      metadata: {
        source: "toolbox-result",
        resultType: input.isVideo ? "video" : "image",
        ...input.metadata,
      },
    });
    return "server";
  } catch {
    return "local";
  }
}
