import { PDFDocument } from 'pdf-lib';

/**
 * Optimizes and embeds a PNG blob into a PDF document with high-quality settings.
 * Handles scaling to fit target page dimensions while maintaining aspect ratio.
 * 
 * @param {PDFDocument} pdfDoc - The target PDFDocument instance
 * @param {Blob|ArrayBuffer} imageSource - The image data
 * @param {Object} options - { width, height, quality }
 * @returns {Promise<PDFImage>} The embedded PDFImage object
 */
export const embedHighQualityImage = async (pdfDoc, imageSource, options = {}) => {
  try {
    let imageBytes;
    
    if (imageSource instanceof Blob) {
      imageBytes = await imageSource.arrayBuffer();
    } else {
      imageBytes = imageSource;
    }

    // Embed PNG. PDF-lib embeds PNGs losslessly by default, 
    // effectively ignoring 'quality' param which usually applies to JPEGs.
    // However, ensuring the source was generated at high DPI (via html2canvas scale)
    // is the key. Here we focus on embedding it correctly.
    const embeddedImage = await pdfDoc.embedPng(imageBytes);

    // Log optimization details
    console.log(`Embedded Image: Original Size ${embeddedImage.width}x${embeddedImage.height}`);

    return embeddedImage;
  } catch (error) {
    console.error("Error embedding high-quality image:", error);
    throw error;
  }
};

/**
 * Calculates optimal dimensions to fit an image into a page maintaining aspect ratio.
 */
export const getOptimalImageDimensions = (img, pageWidth, pageHeight) => {
  if (!img) return { width: 0, height: 0 };

  const imgRatio = img.width / img.height;
  const pageRatio = pageWidth / pageHeight;

  let finalWidth, finalHeight;

  // If image is wider relative to page
  if (imgRatio > pageRatio) {
    finalWidth = pageWidth;
    finalHeight = pageWidth / imgRatio;
  } else {
    finalHeight = pageHeight;
    finalWidth = pageHeight * imgRatio;
  }

  return { width: finalWidth, height: finalHeight };
};