from flask import Flask, request, jsonify
from PIL import Image
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
import os
import time
import requests
from PyPDF2 import PdfReader, PdfWriter

app = Flask(__name__)

UPLOAD_DIR = 'uploads/'
def ensure_directory(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)

ensure_directory(UPLOAD_DIR)

def add_image_to_pdf(c, img_path, width, height):
    with Image.open(img_path) as img:
        img_width, img_height = img.size
        aspect_ratio = img_width / img_height
        if aspect_ratio > width / height:
            new_width = width
            new_height = width / aspect_ratio
        else:
            new_height = height
            new_width = height * aspect_ratio
        c.drawImage(img_path, 0, height - new_height, new_width, new_height)
        c.showPage()

def add_pdf_to_pdf(writer, pdf_path):
    reader = PdfReader(pdf_path)
    num_pages = len(reader.pages)
    print(f"Adding {num_pages} pages from {pdf_path} to the final PDF.")
    for page_num in range(num_pages):
        writer.add_page(reader.pages[page_num])

def process_files(file_storage_list, url_list):
    timestamp = int(time.time() * 1000)
    temp_pdf_path = f'generated_files/temp_{timestamp}.pdf'
    final_pdf_path = f'generated_files/document_{timestamp}.pdf'
    ensure_directory(os.path.dirname(final_pdf_path))

    temp_pdf_writer = PdfWriter()
    c = canvas.Canvas(temp_pdf_path, pagesize=A4)
    width, height = A4

    # Process uploaded files
    for file_storage in file_storage_list:
        file_name = file_storage.filename
        file_type = file_storage.content_type
        file_content = file_storage.read()

        tmp_file_path = os.path.join(UPLOAD_DIR, file_name)
        with open(tmp_file_path, 'wb') as f:
            f.write(file_content)

        if file_type.startswith('image'):
            add_image_to_pdf(c, tmp_file_path, width, height)
        elif file_type == 'application/pdf':
            tmp_pdf_path = os.path.join(UPLOAD_DIR, f'tmp_{file_name}')
            with open(tmp_pdf_path, 'wb') as f:
                f.write(file_content)
            add_pdf_to_pdf(temp_pdf_writer, tmp_pdf_path)
        else:
            print(f"Tipo de archivo no soportado: {file_type}")

    # Process URLs
    for url in url_list:
        response = requests.get(url)
        content_type = response.headers['Content-Type']
        if content_type.startswith('image'):
            tmp_img_path = os.path.join(UPLOAD_DIR, f'tmp_img_{timestamp}')
            with open(tmp_img_path, 'wb') as f:
                f.write(response.content)
            add_image_to_pdf(c, tmp_img_path, width, height)
        elif content_type == 'application/pdf':
            tmp_pdf_path = os.path.join(UPLOAD_DIR, f'tmp_pdf_{timestamp}.pdf')
            with open(tmp_pdf_path, 'wb') as f:
                f.write(response.content)
            add_pdf_to_pdf(temp_pdf_writer, tmp_pdf_path)
        else:
            print(f"Tipo de contenido no soportado: {content_type}")

    c.save()
    
    # Merge PDFs
    final_writer = PdfWriter()
    if os.path.exists(temp_pdf_path):
        temp_reader = PdfReader(temp_pdf_path)
        for page in temp_reader.pages:
            final_writer.add_page(page)

    # Add pages from the temp_pdf_writer
    for page_num in range(len(temp_pdf_writer.pages)):
        final_writer.add_page(temp_pdf_writer.pages[page_num])

    with open(final_pdf_path, 'wb') as f:
        final_writer.write(f)

    # Clean up
    os.remove(temp_pdf_path)
    for file_storage in file_storage_list:
        os.remove(os.path.join(UPLOAD_DIR, file_storage.filename))
    for url in url_list:
        if url.startswith('image'):
            os.remove(os.path.join(UPLOAD_DIR, f'tmp_img_{timestamp}'))
        elif url.startswith('application/pdf'):
            os.remove(os.path.join(UPLOAD_DIR, f'tmp_pdf_{timestamp}.pdf'))

    return final_pdf_path

@app.route('/upload', methods=['POST'])
def upload():
    files = request.files
    urls = request.form.getlist('urls')

    file_storage_list = []
    for key in files:
        file_storage_list.append(files[key])

    # Imprimir los archivos recibidos para depuración
    print("Archivos recibidos:")
    for file in file_storage_list:
        print(f"Nombre del archivo: {file.filename}")
        print(f"Tipo de archivo: {file.content_type}")
        # Reposicionar el puntero del archivo al inicio después de leer su información
        file.seek(0)

    # Imprimir URLs recibidas para depuración
    print("URLs recibidas:")
    for url in urls:
        print(url)
        
    if not file_storage_list and not urls:
        return jsonify({"error": "No files or URLs provided"}), 400

    pdf_file_path = process_files(file_storage_list, urls)
    
    return jsonify({"message": "Archivos procesados exitosamente.", "pdf_url": pdf_file_path})



if __name__ == "__main__":
    app.run(debug=True)
