import type { ToolInput } from "../../core/io/input-types";
import type { ToolResult } from "../../core/io/output-types";
import type { ToolContext } from "../../core/plugins/plugin-types";
import type { ImageEditorOptions } from "./index";

function dataUrlToBlob(dataUrl: string): Blob {
  const [header, payload] = dataUrl.split(",");
  const mimeMatch = header.match(/^data:(.*?);base64$/);
  if (!mimeMatch || !payload) {
    throw new Error("Invalid image export data.");
  }

  const binary = atob(payload);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) {
    bytes[i] = binary.charCodeAt(i);
  }

  return new Blob([bytes], { type: mimeMatch[1] });
}

function extensionForMime(mimeType: ImageEditorOptions["format"]): string {
  if (mimeType === "image/jpeg") return "jpg";
  if (mimeType === "image/webp") return "webp";
  return "png";
}

export async function runImageEditor(
  input: ToolInput,
  options: ImageEditorOptions,
  context: ToolContext
): Promise<ToolResult> {
  if (!options.dataUrl) {
    throw new Error("No edited image is ready to export.");
  }

  context.reportProgress({ percentage: 60, message: "Preparing export..." });

  const blob = dataUrlToBlob(options.dataUrl);
  const sourceName = input.files?.[0]?.name ?? "image";
  const baseName = sourceName.includes(".")
    ? sourceName.slice(0, sourceName.lastIndexOf("."))
    : sourceName;
  const name = `${baseName}_edited.${extensionForMime(options.format)}`;

  context.reportProgress({ percentage: 100, message: "Done" });

  return {
    type: "files",
    files: [
      {
        name,
        mimeType: options.format,
        blob,
        sizeBefore: input.files?.[0]?.size,
        sizeAfter: blob.size,
      },
    ],
  };
}
