import argparse
import os
from pptx import Presentation
from pptx.util import Pt
from pptx.enum.text import PP_ALIGN
from pptx.dml.color import RGBColor

def parse_args():
    parser = argparse.ArgumentParser(description="PowerPointノートをスライドに字幕として追加するツール")
    parser.add_argument("infile", help="入力PowerPointファイル（.pptx）")
    parser.add_argument("-o", "--outfile", help="出力ファイル名（省略時は -note-added.pptx を付加）")
    args = parser.parse_args()

    if not args.outfile:
        base, ext = os.path.splitext(args.infile)
        args.outfile = f"{base}-note-added.pptx"

    return args.infile, args.outfile

def add_notes_as_subtitles(infile, outfile):
    prs = Presentation(infile)

    # スライドサイズ取得（デフォルトは 10 x 7.5 インチ）
    slide_width = prs.slide_width
    slide_height = prs.slide_height

    # 字幕スタイル設定
    FONT_NAME = "メイリオ"
    FONT_SIZE = Pt(20)
    FONT_COLOR = RGBColor(255, 255, 255)  # 白
    BACKGROUND_COLOR = RGBColor(0, 0, 0)  # 黒

    for slide in prs.slides:
        notes_slide = slide.notes_slide
        note_text = notes_slide.notes_text_frame.text.strip()

        if note_text:
            # テキストボックスの位置とサイズ（スライド下部に幅いっぱい）
            left = Pt(0)
            top = slide_height - Pt(60)  # 下から60ptの位置
            width = slide_width
            height = Pt(60)

            textbox = slide.shapes.add_textbox(left, top, width, height)
            textbox.fill.solid()
            textbox.fill.fore_color.rgb = BACKGROUND_COLOR

            text_frame = textbox.text_frame
            text_frame.word_wrap = True
            text_frame.text = note_text
            text_frame.margin_left = Pt(10)
            text_frame.margin_right = Pt(10)
            text_frame.paragraphs[0].alignment = PP_ALIGN.LEFT

            run = text_frame.paragraphs[0].runs[0]
            run.font.name = FONT_NAME
            run.font.size = FONT_SIZE
            run.font.color.rgb = FONT_COLOR

    prs.save(outfile)
    print(f"保存しました: {outfile}")

if __name__ == "__main__":
    infile, outfile = parse_args()
    add_notes_as_subtitles(infile, outfile)
