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

export async function runPdfMerger(
  input: ToolInput,
  _options: unknown,
  context: ToolContext
): Promise<ToolResult> {
  const files = input.files;

  if (!files || !Array.isArray(files) || files.length === 0) {
    throw new Error("No files provided for merging.");
  }

  try {
    const mergedPdf = await PDFDocument.create();

    for (let i = 0; i < files.length; i++) {
      const file = files[i];

      context.reportProgress({
        percentage: (i / files.length) * 100,
        message: `Merging ${file.name} (${i + 1}/${files.length})...`,
      });

      const fileBuffer = await file.arrayBuffer();
      const pdfDoc = await PDFDocument.load(new Uint8Array(fileBuffer));

      const copiedPages = await mergedPdf.copyPages(
        pdfDoc,
        pdfDoc.getPageIndices()
      );
      copiedPages.forEach((page) => mergedPdf.addPage(page));
    }

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

    const mergedPdfBytes = await mergedPdf.save();
    // TS DOM lib workaround for Uint8Array
    const blob = new Blob([mergedPdfBytes as unknown as BlobPart], { type: "application/pdf" });

    return {
      type: "files",
      files: [
        {
          name: "merged_document.pdf",
          mimeType: "application/pdf",
          blob: blob,
          sizeAfter: blob.size,
        },
      ],
    };
  } catch (error) {
    console.error("PDF Merge Error:", error);
    throw error instanceof Error ? error : new Error("Unknown error occurred during PDF merging");
  }
}
