import type { PublishCommunityCaseInput } from "../../api/communityClient";
import type { WebCanvasWorkflow } from "../../types";

interface UploadedWorkflowAsset {
  url: string;
  ossKey?: string;
  fileName: string;
}

interface CanvasCommunityCaseInput {
  workflow: WebCanvasWorkflow;
  projectId?: string | null;
  uploadedWorkflow: UploadedWorkflowAsset;
}

function getCanvasWorkflowCoverUrl(workflow: WebCanvasWorkflow): string {
  return workflow.nodes.find((node) => node.previewUrl)?.previewUrl || "";
}

function shortWorkflowDescription(workflow: WebCanvasWorkflow): string {
  const promptNode = workflow.nodes.find((node) => node.detail.trim());
  return promptNode?.detail.trim().slice(0, 120) || `包含 ${workflow.nodes.length} 个节点的画布工作流`;
}

export function textToDataUrl(text: string, mimeType: string): string {
  const bytes = new TextEncoder().encode(text);
  let binary = "";
  bytes.forEach((byte) => {
    binary += String.fromCharCode(byte);
  });
  return `data:${mimeType};base64,${btoa(binary)}`;
}

export function buildCanvasWorkflowJson(workflow: WebCanvasWorkflow): string {
  return JSON.stringify(workflow, null, 2);
}

export function buildWorkflowFileName(title: string): string {
  const normalized = title.trim().replace(/[\\/:*?"<>|]+/g, "-").replace(/\s+/g, "-");
  return `${(normalized || "canvas-workflow").slice(0, 72)}.json`;
}

export function buildCanvasCommunityCaseInput({
  workflow,
  projectId,
  uploadedWorkflow,
}: CanvasCommunityCaseInput): PublishCommunityCaseInput {
  const title = workflow.title.trim() || "画布工作流";
  const coverUrl = getCanvasWorkflowCoverUrl(workflow);
  const workflowAsset = {
    assetType: "workflow" as const,
    title,
    url: uploadedWorkflow.url,
    ossKey: uploadedWorkflow.ossKey,
    metadata: {
      workflow,
      fileName: uploadedWorkflow.fileName,
      contentType: "application/json",
    },
  };
  const coverAsset = coverUrl
    ? [
        {
          assetType: "cover" as const,
          title: `${title} 封面`,
          url: coverUrl,
          metadata: { source: "workflow-preview" },
        },
      ]
    : [];

  return {
    projectId: projectId || workflow.id,
    title,
    description: workflow.description.trim() || shortWorkflowDescription(workflow),
    coverUrl: coverUrl || null,
    tags: ["工作流案例", "画布页面社区"],
    metadata: {
      source: "canvas-workflow-export",
      communitySurface: "canvas",
      category: "工作流案例",
      workflow,
      workflowSnapshot: workflow,
      workflowData: workflow,
      workflowOssKey: uploadedWorkflow.ossKey || null,
      workflowUrl: uploadedWorkflow.url || null,
      nodeCount: workflow.nodes.length,
      edgeCount: workflow.edges.length,
      settings: workflow.settings,
    },
    assets: [workflowAsset, ...coverAsset],
  };
}
