#!/usr/bin/env python3

def get_resource_path(filename):
    """Get absolute path to resource, works for dev and for PyInstaller"""
    import os, sys
    try:
        base_path = sys._MEIPASS
    except AttributeError:
        base_path = os.path.dirname(os.path.abspath(__file__)) 
    return os.path.join(base_path, filename)

def get_base_path():
    """Get absolute path to executable, works for dev and for PyInstaller"""
    import os, sys
    if hasattr(sys, 'frozen'):
        base_path = os.path.dirname(sys.executable)
    else:
        base_path = os.path.dirname(os.path.abspath('.'))
    return base_path
           
def pdf_to_img(input_pdf_path, dpi=300):
    """Convert pdf to images"""
    import os
    import pdf2image
    img_paths = []
    try: 
        images = pdf2image.convert_from_path(input_pdf_path, dpi=dpi)  
        img_dir = os.path.join(get_base_path(), 'tmp', 'imgs')
        os.makedirs(img_dir, exist_ok=True)
        for i, image in enumerate(images):
            img_path = os.path.join(img_dir, 'img_%03d.png' % i)
            image.save(img_path, 'PNG')
            img_paths.append(img_path)
    except Exception as e:
        print(e)        
    return img_paths    
        
def imgs_to_pdf(img_paths, output_pdf_path,):
    """Convert images to pdf"""
    import os
    import img2pdf
    output_path = os.path.dirname(output_pdf_path)
    os.makedirs(output_path, exist_ok=True)
    
    # A4尺寸 - 21cm×29.7cm（210mm×297mm）
    A4_WIDTH = img2pdf.mm_to_pt(210)
    A4_HEIGHT = img2pdf.mm_to_pt(180)
    page_size = (A4_WIDTH, A4_HEIGHT)
    
    layout_fun = img2pdf.get_layout_fun(page_size)
    with open(output_pdf_path, "wb") as f:
        # 指定 fit='into' 以保持宽高比
        f.write(img2pdf.convert(img_paths, layout_fun=layout_fun))
    for img_path in img_paths:
        os.remove(img_path) 
    os.removedirs(os.path.dirname(img_paths[0]))        
        
def convert(input_pdf_path, output_pdf_path, dpi=300):    
    img_paths = pdf_to_img(input_pdf_path, dpi)
    imgs_to_pdf(img_paths, output_pdf_path)

def check_poppler_installed():
    import shutil
    import platform

    """Check if poppler is installed on the system."""
    # Check for pdftoppm or pdfinfo (part of poppler-utils)
    if shutil.which("pdftoppm") is None and shutil.which("pdfinfo") is None:
        system = platform.system()
        if system == "Windows":
            raise RuntimeError(
                "Poppler is not installed. Please install Poppler for Windows:\n"
                "https://github.com/oschwartz10612/poppler-windows/releases/"
            )
        elif system == "Linux":
            raise RuntimeError(
                "Poppler is not installed. Please install Poppler using your package manager:\n"
                "Ubuntu/Debian: sudo apt-get install poppler-utils\n"
                "CentOS/RHEL: sudo yum install poppler-utils"
            )
        elif system == "Darwin":  # macOS
            raise RuntimeError(
                "Poppler is not installed. Please install Poppler using Homebrew:\n"
                "brew install poppler"
            )
        else:
            raise RuntimeError("Unsupported operating system. Please manually install Poppler.")

def remove_pycache(root_dir='.'):
    import os
    for dirpath, dirnames, filenames in os.walk(root_dir):
        print(dirpath, dirnames, filenames)
        # for dirname in dirnames:
        #     if dirname.endswith("__pycache__"):
        #         os.rmdir(os.path.join(dirpath, dirname))

if __name__ == "__main__":
    import sys
    if len(sys.argv) < 3:
        print("Usage: pdf2img2pdf.py <input.pdf> <output.pdf> <dpi>")
    else:
        try:
            # Check if poppler is installed before proceeding
            check_poppler_installed()
            convert(sys.argv[1], sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else 100)
        except Exception as e:
            print(e)    