import fitz
from pptx import Presentation
from pptx.util import Inches
import io

PDF_PATH = r"C:\Users\jhodgkin\Documents\dev\primary-song-slides\songs\search-ponder-and-pray\SearchPonderandPrayWithLyrics.pdf"
OUT_PATH = r"C:\Users\jhodgkin\Documents\dev\primary-song-slides\songs\search-ponder-and-pray\SearchPonderAndPray.pptx"
DPI = 96

SLIDE_W = Inches(13.333)
SLIDE_H = Inches(7.5)


def render_page(page):
    mat = fitz.Matrix(DPI / 72, DPI / 72)
    pix = page.get_pixmap(matrix=mat, alpha=False)
    return io.BytesIO(pix.tobytes("jpeg", jpg_quality=85)), pix.width, pix.height


def add_slide(doc, prs, blank_layout, page_idx):
    page = doc[page_idx]
    img_bytes, pw, ph = render_page(page)
    slide = prs.slides.add_slide(blank_layout)

    aspect = pw / ph
    h = SLIDE_H
    w = int(h * aspect)
    if w > SLIDE_W:
        w = SLIDE_W
        h = int(w / aspect)
    left = (SLIDE_W - w) // 2
    top = (SLIDE_H - h) // 2
    slide.shapes.add_picture(img_bytes, left, top, width=w, height=h)

    print(f"  Slide {len(prs.slides):2d} (pg {page_idx+1:2d})")


def main():
    doc = fitz.open(PDF_PATH)
    prs = Presentation()
    prs.slide_width = SLIDE_W
    prs.slide_height = SLIDE_H
    blank_layout = prs.slide_layouts[6]

    # Lyrics are embedded in the artwork, so every page is one slide
    for page_idx in range(len(doc)):
        add_slide(doc, prs, blank_layout, page_idx)

    prs.save(OUT_PATH)
    print(f"\nSaved: {OUT_PATH}  ({len(doc)} slides)")


if __name__ == "__main__":
    main()
