#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
=============================================================================
REGISTER INTRO PROMPTS INTO KIEU STORY CATALOGS (FLOWKIT 3-BEAT STANDARD)
=============================================================================
Đăng ký chính thức 2 Shot Intro mở đầu phim vào các kho prompt của dự án:
- ep01_intro_shot01: Dải lụa thanh xuân lướt qua mặt hồ sương sớm
- ep01_intro_shot02: Dải lụa xoáy khởi nguyên & Khai mở biểu trưng "Thập Ngũ Niên"
=============================================================================
"""

import sys
import json
from pathlib import Path

if sys.platform == "win32":
    try:
        sys.stdout.reconfigure(encoding="utf-8")
        sys.stderr.reconfigure(encoding="utf-8")
    except Exception:
        pass

BASE_DIR = Path("c:/Projects/KieuStory")
MUSE_MASTER = BASE_DIR / "02_AI_Prompts" / "muse_ai_video_prompts.json"
BANANA_MASTER = BASE_DIR / "02_AI_Prompts" / "gemini_banana_prompts.json"
EP01_MUSE = BASE_DIR / "episodes" / "ep01" / "prompts" / "muse_prompts.json"
EP01_BANANA = BASE_DIR / "episodes" / "ep01" / "prompts" / "banana_prompts.json"

INTRO_MUSE_PROMPTS = {
    "ep01_intro_shot01": {
        "scene_title": "EP01 Intro Shot 01: DẢI LỤA THANH XUÂN LƯỚT QUA MẶT HỒ SƯƠNG SỚM",
        "mode": "Image-to-Video",
        "reference_start_frame": "04_Assets/keyframes/ep01_intro_shot01/start_frame_720p.png",
        "motion_prompt": "[Beat 1 (0-3s) - Thiết lập]: Mặt hồ yên ả lúc bình minh, làn sương sớm bảng lảng trôi nhẹ trên mặt nước trong vắt, cánh hoa đào và hoa lê rơi lơ lửng tạo gợn sóng tinh tế, dải lụa màu xanh ngọc bích từ mép khung hình lướt nhẹ vào làn sương.\n[Beat 2 (3-6s) - Kịch tính & Cảm xúc]: Dải lụa xanh ngọc bích uốn lượn hình chữ S mềm mại, tà lụa thêu chỉ vàng óng ánh bay lướt sát mặt nước, xuyên qua rặng liễu rủ trước mái đình tạ cổ kính cong vút.\n[Beat 3 (6-10s) - Lắng đọng & Nối tiếp]: Dải lụa bay vút lên cao về phía cột đình son đỏ, gió cuốn tà lụa mở rộng không gian, ổn định tư thế để nối tiếp hoàn hảo sang Shot 2.\n[Chuyển động Camera]: Slow Cinematic Tracking / Crane Down 35mm, góc máy mượt mà từ trên cao hạ dần xuống mặt nước theo quỹ đạo dải lụa. Quy tắc âm thanh: Tuyệt đối KHÔNG sinh nhạc nền (no music/BGM), không âm thanh điện tử, không tạp âm rè nhiễu. Chỉ sinh âm thanh môi trường nước và tiếng lụa mềm bay trong gió.",
        "camera_motion": "Slow Cinematic Tracking / Crane Down 35mm",
        "duration_sec": 10,
        "audio_prompt": "Âm thanh: Tiếng nước chảy róc rách trong vắt, bọt nước reo, sóng hồ lăn tăn ven bờ, tiếng gió sớm luồn qua rặng liễu, tiếng dải lụa mềm bay lướt trong gió.. Quy tắc âm thanh: Tuyệt đối KHÔNG sinh nhạc nền có tiếng đàn tỳ bà gảy dây (no pipa/tỳ bà plucking), không âm thanh điện tử, không tạp âm rè nhiễu. Chỉ sinh âm thanh tiếng nước chảy tự nhiên (foley, ambience water stream) và thảm âm thanh tĩnh lặng.",
        "target_video_file": "ep01_intro_shot01_10s_master.mp4",
        "reverse_motion": False,
        "video_engine": "muse_api",
        "flowkit_pacing": "3_beat_cinematic",
        "start_frame_strategy": "GEMINI_BANANA_KEYFRAME",
        "turnaround_view": None
    },
    "ep01_intro_shot02": {
        "scene_title": "EP01 Intro Shot 02: DẢI LỤA XOÁY KHỞI NGUYÊN & KHAI MỞ BIỂU TRƯNG THẬP NGŨ NIÊN",
        "mode": "Image-to-Video",
        "reference_start_frame": "Frame cuối (239/10s) của ep01_intro_shot01_10s_master.mp4: Tiếp nối mượt mà vị trí dải lụa, góc nhìn và hướng chuyển động.",
        "motion_prompt": "[Beat 1 (0-3s) - Thiết lập]: Tiếp nối mượt mà từ frame trước, dải lụa xanh ngọc bích cuộn xoáy lên không trung tạo thành hình vòng cung chữ S ôm trọn bầu trời kinh kỳ.\n[Beat 2 (3-6s) - Kịch tính & Cảm xúc]: Từ tâm dải lụa, một luồng ánh sáng hoàng kim bùng nổ rực rỡ, bụi vàng lấp lánh tỏa ra không gian; tựa đề phim thư pháp cổ phong uy nghi 'Thập Ngũ Niên' dát vàng kim viền chu sa đỏ dần hiển lộ oai nghiêm, cánh hoa lê trắng muốt rơi nhẹ nhàng.\n[Beat 3 (6-10s) - Lắng đọng & Nối tiếp]: Dòng chữ 'Thập Ngũ Niên' định vị trang trọng giữa không gian đình tạ và mặt hồ thanh bình, ánh sáng lấp lánh dịu dần, tạo ấn tượng mở màn điện ảnh kinh điển và sâu lắng, dẫn truyền êm ái sang Prologue.\n[Chuyển động Camera]: Cinematic Push-in / Title Reveal 35mm, máy quay tiến chậm rãi vào tâm điểm luồng sáng hoàng kim. Quy tắc âm thanh: Tuyệt đối KHÔNG sinh nhạc nền có tiếng đàn tỳ bà, không âm thanh điện tử, không tạp âm rè nhiễu. Chỉ sinh foley dải lụa, tiếng nước chảy và thảm âm thanh thiền định hoài niệm đồng điệu với Prologue.",
        "camera_motion": "Cinematic Push-in / Title Reveal 35mm",
        "duration_sec": 10,
        "audio_prompt": "Âm thanh: Tiếng lụa bay xoáy trong gió, luồng sáng bùng nổ lung linh (celestial shimmer), tiếng chuông ngọc ngân vang thanh tịnh, tiếng nước chảy róc rách và thảm âm thanh cổ phong dịu dần để nối tiếp mượt mà vào tiếng ngâm Kiều của Prologue.. Quy tắc âm thanh: Tuyệt đối KHÔNG sinh tiếng đàn tỳ bà gảy dây, không âm thanh điện tử.",
        "target_video_file": "ep01_intro_shot02_10s_master.mp4",
        "reverse_motion": False,
        "video_engine": "muse_api",
        "flowkit_pacing": "3_beat_cinematic",
        "start_frame_strategy": "HEAD_TAIL_PREV_FRAME",
        "turnaround_view": None
    }
}

INTRO_BANANA_PROMPTS = {
    "ep01_intro_shot01": {
        "character_anchor": "none",
        "environment_anchor": "mat_ho_suong_som_dinh_ta",
        "prompt": "Cinematic 8k masterpiece, photorealistic medieval Vietnamese and East Asian historical drama aesthetic, authentic Annam period architecture, 35mm cinema film grain, anamorphic lens, natural volumetric lighting, color graded for IMAX. Serene morning mist rising over a tranquil pond with floating lotus leaves, weeping willow trees framing ancient red lacquered pavilions. A vibrant emerald jade silk ribbon embroidered with delicate golden thread drifts gracefully into frame over the glassy water surface. Falling white pear blossoms and pink peach petals ripple the water gently. Golden sunrise rays piercing the morning haze, breathtaking cinematic poetry. --no modern clothing, western features, modern buildings, 3D polygon, text, watermark --ar 16:9",
        "resolution": "1280x720",
        "start_frame_strategy": "GEMINI_BANANA_KEYFRAME",
        "turnaround_view": None
    },
    "ep01_intro_shot02": {
        "character_anchor": "none",
        "environment_anchor": "mat_ho_suong_som_dinh_ta",
        "prompt": "Cinematic 8k masterpiece, photorealistic medieval Vietnamese and East Asian historical drama aesthetic, authentic Annam period architecture, 35mm cinema film grain, anamorphic lens, natural volumetric lighting. Seamless continuation: The emerald green silk ribbon swirls gracefully upward in front of the red wooden pavilion. From the vortex of the ribbon, a radiant burst of ethereal golden light and glowing celestial particles explodes over the mist-covered lake. Majestically revealed in ancient calligraphic cinnabar red with embossed imperial gold trimming is the grand title 'Thập Ngũ Niên', floating elegantly above the serene waters. Floating red ribbon accents and fluttering white pear petals, awe-inspiring cinematic title reveal. --no modern clothing, western features, 3D polygon, watermark --ar 16:9",
        "resolution": "1280x720",
        "start_frame_strategy": "HEAD_TAIL_PREV_FRAME",
        "turnaround_view": None
    }
}

def update_json_file(file_path: Path, new_data: dict, section_key: str = None):
    if not file_path.exists():
        return
    try:
        content = json.loads(file_path.read_text(encoding="utf-8"))
        if section_key:
            if section_key not in content:
                content[section_key] = {}
            content[section_key].update(new_data)
        else:
            content.update(new_data)
        file_path.write_text(json.dumps(content, ensure_ascii=False, indent=2), encoding="utf-8")
        print(f"[✓] Đã cập nhật: {file_path}")
    except Exception as e:
        print(f"[!] Lỗi cập nhật {file_path}: {e}")

if __name__ == "__main__":
    print("[*] Đang đăng ký Intro Shots vào các kho Prompt...")
    # Update motion_prompts section
    update_json_file(MUSE_MASTER, INTRO_MUSE_PROMPTS, section_key="motion_prompts")
    update_json_file(EP01_MUSE, INTRO_MUSE_PROMPTS, section_key="motion_prompts")
    # Also keep at root if desired
    update_json_file(MUSE_MASTER, INTRO_MUSE_PROMPTS)
    update_json_file(EP01_MUSE, INTRO_MUSE_PROMPTS)

    # Banana prompts both at root and in ep01_start_frames
    update_json_file(BANANA_MASTER, INTRO_BANANA_PROMPTS, section_key="ep01_start_frames")
    update_json_file(BANANA_MASTER, INTRO_BANANA_PROMPTS)
    update_json_file(EP01_BANANA, INTRO_BANANA_PROMPTS)
    print("[✓] Hoàn tất đăng ký Intro Prompts vào hệ thống!")
