import os
from PyPDF2 import PdfReader, PdfWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4

GENERATED_FOLDER = os.path.abspath(
    os.path.join(os.path.dirname(__file__), "..", "generated_pdfs")
)

def create_watermark_pdf(watermark_path, text="CANCELLED"):
    c = canvas.Canvas(watermark_path, pagesize=A4)
    c.setFont("Helvetica-Bold", 80)
    c.setFillGray(0.6)  # Light gray text
    c.saveState()
    c.translate(300, 400)
    c.rotate(45)
    c.drawCentredString(0, 0, text)
    c.restoreState()
    c.save()

def apply_watermark(input_pdf_path, output_pdf_path, watermark_pdf_path):
    reader = PdfReader(input_pdf_path)
    watermark = PdfReader(watermark_pdf_path).pages[0]
    writer = PdfWriter()

    for page in reader.pages:
        page.merge_page(watermark)
        writer.add_page(page)

    with open(output_pdf_path, "wb") as f:
        writer.write(f)

def cancel_order_pdf(order_filename):
    # File paths
    input_pdf_path = os.path.join(GENERATED_FOLDER, order_filename)
    output_pdf_path = input_pdf_path
    watermark_pdf_path = os.path.join(GENERATED_FOLDER, "temp_watermark.pdf")
    print(watermark_pdf_path)
    # Check if file exists
    if not os.path.isfile(input_pdf_path):
        raise FileNotFoundError(f"Original order PDF not found: {input_pdf_path}")

    # Create watermark and apply it
    create_watermark_pdf(watermark_pdf_path, text="CANCELLED")
    apply_watermark(input_pdf_path, output_pdf_path, watermark_pdf_path)

    # Optionally remove temp watermark
    os.remove(watermark_pdf_path)

    return output_pdf_path

# Example usage:
if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2:
        print("Usage: python cancel_order.py <order_filename>")
    else:
        try:
            result_path = cancel_order_pdf(sys.argv[1])
            print(f"Cancelled PDF created: {result_path}")
        except Exception as e:
            print(f"Error: {e}")