import os
import sys
import pyttsx3
import win32com.client


speak_rate = 150

def generate_audio_files(pptx_path, output_dir, rate=180, voice_token=None):
    ppt = win32com.client.Dispatch("PowerPoint.Application")
    ppt.Visible = True
    pres = ppt.Presentations.Open(os.path.abspath(pptx_path))

    os.makedirs(output_dir, exist_ok=True)
    engine = pyttsx3.init()
    engine.setProperty("rate", rate)
    if voice_token:
        engine.setProperty("voice", voice_token)

    audio_tasks = []
    for idx, slide in enumerate(pres.Slides, start=1):
        notes = ""
        for shp in slide.NotesPage.Shapes:
            if shp.Type == 14 and shp.PlaceholderFormat.Type == 2:
                notes = shp.TextFrame.TextRange.Text.strip()
                break
        if not notes:
            print(f"Slide {idx}: ノートなし → スキップ")
            continue

        wav_path = os.path.join(output_dir, f"slide{idx}.wav")
        engine.save_to_file(notes, wav_path)
        audio_tasks.append((idx, wav_path))
        print(f"  queued: {wav_path}")

    if audio_tasks:
        print("\nSynthesizing all queued audio...")
        engine.runAndWait()
        engine.stop()

    pres.Close()
    ppt.Quit()
    print(f"\n✅ 音声ファイル生成完了 ({len(audio_tasks)}件)")
    return audio_tasks


def link_audio_autoplay(pptx_path, audio_tasks, output_pptx):
    ppt = win32com.client.Dispatch("PowerPoint.Application")
    ppt.Visible = True
    pres = ppt.Presentations.Open(os.path.abspath(pptx_path))

    for idx, wav_path in audio_tasks:
        slide = pres.Slides(idx)

        # --- スライドサイズ取得 ---
        slide_width = pres.PageSetup.SlideWidth
        slide_height = pres.PageSetup.SlideHeight

        # --- 右下にスピーカーアイコン ---
        icon_size = 40
        left = slide_width - icon_size - 10
        top = slide_height - icon_size - 10

        shape = slide.Shapes.AddMediaObject2(
            os.path.abspath(wav_path),
            LinkToFile=True,
            SaveWithDocument=False,
            Left=left, Top=top,
            Width=icon_size, Height=icon_size
        )

        # --- メディア再生設定 ---
        shape.AnimationSettings.PlaySettings.PlayOnEntry = True
        shape.AnimationSettings.PlaySettings.HideWhileNotPlaying = False
        shape.AnimationSettings.PlaySettings.LoopUntilStopped = False

        # --- 自動再生アニメーション追加 ---
        effect = slide.TimeLine.MainSequence.AddEffect(
            shape,
            9,  # msoAnimEffectMediaPlay
            0,
            1   # msoAnimTriggerAfterPrevious
        )

        # これがないとスライドショーで再生されない
        effect.Timing.TriggerType = 2  # msoAnimTriggerWithPrevious

        print(f"Slide {idx}: added autoplay effect ({wav_path})")

    pres.SaveAs(os.path.abspath(output_pptx))
    pres.Close()
    ppt.Quit()
    print(f"\n✅ PowerPoint更新完了（自動再生確認済み）: {output_pptx}")


def main():
    global speak_rate

    if len(sys.argv) < 4:
        print("使い方: python ppt_notes_audio_autoplay.py input.pptx audio_dir output.pptx")
        sys.exit(1)

    pptx_file = sys.argv[1]
    audio_dir = sys.argv[2]
    output_pptx = sys.argv[3]
    if len(sys.argv) > 4: speak_rate = int(sys.argv[4])

    voice = 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\TTS_MS_JA_JP_HARUKA_11.0'
    tasks = generate_audio_files(pptx_file, audio_dir, voice_token=voice, rate = speak_rate)
    link_audio_autoplay(pptx_file, tasks, output_pptx)


if __name__ == "__main__":
    main()
