from pathlib import Path
from pptx import Presentation
from pptx.util import Inches


BASE_PPTX = Path("/Users/jack/Library/Containers/com.tencent.xinWeChat/Data/Documents/xwechat_files/aqua118_1a62/msg/file/2026-09/康比特【AI智慧营养超级食堂】解决方案_2608.pptx")
ROOT = Path(__file__).resolve().parent
IMAGE_DIR = ROOT / "generated" / "images"
OUT_DIR = ROOT / "generated" / "pptx"
OUT_PPTX = OUT_DIR / "康比特AI智慧营养超级食堂_五大场景前置页_v0.1.pptx"


def find_blank_layout(prs):
    return min(prs.slide_layouts, key=lambda layout: len(layout.placeholders))


def main():
    if not BASE_PPTX.exists():
        raise FileNotFoundError(BASE_PPTX)
    images = sorted(IMAGE_DIR.glob("*.png"))
    if len(images) != 7:
        raise RuntimeError(f"expected 7 generated images, found {len(images)}")

    OUT_DIR.mkdir(parents=True, exist_ok=True)
    prs = Presentation(str(BASE_PPTX))
    slide_width = prs.slide_width
    slide_height = prs.slide_height
    blank = find_blank_layout(prs)

    new_slide_ids = []
    for image in images:
        slide = prs.slides.add_slide(blank)
        for shape in list(slide.shapes):
            if shape.is_placeholder:
                sp = shape._element
                sp.getparent().remove(sp)
        slide.shapes.add_picture(str(image), 0, 0, width=slide_width, height=slide_height)
        new_slide_ids.append(prs.slides._sldIdLst[-1])

    # Insert after original P14 so the scene pages become the front explanation
    # before the original product/function section.
    sld_id_list = prs.slides._sldIdLst
    for sld_id in new_slide_ids:
        sld_id_list.remove(sld_id)

    insert_pos = min(14, len(sld_id_list))
    for offset, sld_id in enumerate(new_slide_ids):
        sld_id_list.insert(insert_pos + offset, sld_id)

    prs.save(str(OUT_PPTX))
    print(OUT_PPTX)


if __name__ == "__main__":
    main()

