#!/usr/bin/python3

import argparse
import zipfile
from svglib.svglib import svg2rlg
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF
from pathlib import Path
import shutil
import tempfile
import sys

def ubz_to_pdf(filepath):
    filepath = Path(filepath)
    if filepath.suffix != '.ubz':
        raise Exception(f'File {filepath} is not a .ubz file. Skipping.')

    with tempfile.TemporaryDirectory(prefix="ubztopdf_") as extract_dir:
        with zipfile.ZipFile(filepath, 'r') as archive:
            archive.extractall(extract_dir)
        
        svgfiles = sorted(Path(extract_dir).glob('*.svg'))
        if not svgfiles:
            raise Exception(f"No .svg files found in {filepath.name}. Skipping.")
        
        # Get page size from first SVG
        drawing = svg2rlg(str(svgfiles[0]))
        if drawing is None:
            raise Exception(f"Could not parse {svgfiles[0]} as SVG.")
        xL, yL, xH, yH = drawing.getBounds()
        pdf_path = filepath.with_suffix('.pdf')
        pdf = canvas.Canvas(str(pdf_path), pagesize=(xH - xL, yH - yL))

        for svgfile in svgfiles:
            drawing = svg2rlg(str(svgfile))
            if drawing is None:
                print(f"Warning: Could not parse {svgfile} as SVG. Skipping.", file=sys.stderr)
                continue
            renderPDF.draw(drawing, pdf, 0, 0)
            pdf.showPage()

        pdf.save()
        print(f"Saved: {pdf_path}")

def main():
    parser = argparse.ArgumentParser(description='Convert .ubz files to PDF.')
    parser.add_argument('files', nargs='+', type=str, help='One or more paths to .ubz files')
    args = parser.parse_args()

    for file in args.files:
        try:
            ubz_to_pdf(file)
        except Exception as e:
            print(str(e), file=sys.stderr)

if __name__ == "__main__":
    main()