import argparse
from PyPDF2 import PdfReader, PdfWriter
from PyPDF2.generic import NameObject, NumberObject
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter

def create_image_overlay(image_path, output_path, position=(100, 100), size=(50, 40)):
    """Create a PDF overlay with the image."""
    c = canvas.Canvas(output_path, pagesize=letter)
    c.drawImage(image_path, position[0], position[1], width=size[0], height=size[1])  # Fixed size: 50x40
    c.save()

def get_field_coordinates(pdf_path, field_name):
    """Get the coordinates of a specific form field."""
    reader = PdfReader(pdf_path)
    for page in reader.pages:
        if "/Annots" in page:
            for annot in page["/Annots"]:
                field = annot.get_object()
                if field.get("/T") == field_name:  # Check the field name
                    rect = field.get("/Rect")  # Get field coordinates
                    return rect
    return None

def replace_form_field_with_image(pdf_path, image_path, output_path, field_name):
    """Replace a specific form field with an image."""
    # Get the coordinates of the form field
    field_rect = get_field_coordinates(pdf_path, field_name)
    if not field_rect:
        print(f"Field '{field_name}' not found.")
        return

    # Calculate the position for the overlay
    x1, y1, x2, y2 = map(float, field_rect)  # Field rectangle
    position = (x1, y1)
    size = (x2 - x1, y2 - y1)

    # Create the overlay
    overlay_pdf = "image_overlay.pdf"
    create_image_overlay(image_path, overlay_pdf, position=position, size=(size[0], size[1]))

    # Merge the overlay into the PDF
    reader = PdfReader(pdf_path)
    writer = PdfWriter()

    overlay = PdfReader(overlay_pdf)
    for i, page in enumerate(reader.pages):
        if "/Annots" in page:
            for annot in page["/Annots"]:
                field = annot.get_object()
                if field.get("/T") == field_name:  # Replace only the page containing the field
                    page.merge_page(overlay.pages[0])
                    flags = field.get("/F", 2)
                    field.update({
                        NameObject("/F"): NumberObject(flags | 2)  # Flag 2: Hidden
                    })
        writer.add_page(page)

    # Save the modified PDF
    with open(output_path, "wb") as f_out:
        writer.write(f_out)

if __name__ == "__main__":
    # Set up argparse to handle command-line arguments
    parser = argparse.ArgumentParser(description="Replace a PDF form field with an image.")
    parser.add_argument("original_pdf", help="Path to the original PDF")
    parser.add_argument("image_path", help="Path to the image to overlay")
    parser.add_argument("final_pdf", help="Path to save the final output PDF")
    parser.add_argument("field_name", help="Name of the field to replace with the image")

    # Parse the arguments
    args = parser.parse_args()

    # Call the function with the arguments
    replace_form_field_with_image(args.original_pdf, args.image_path, args.final_pdf, args.field_name)
