import json
from pathlib import Path

BASE_DIR = Path(r"c:\Projects\KieuStory")
muse_file = BASE_DIR / "02_AI_Prompts" / "muse_ai_video_prompts.json"
ep01_file = BASE_DIR / ".agents" / "teamwork" / "spec_miner_m2_3" / "ep01_muse_prompts_188_shots.json"

with open(muse_file, "r", encoding="utf-8") as f:
    muse_data = json.load(f)

with open(ep01_file, "r", encoding="utf-8") as f:
    ep01_shots = json.load(f)

print("Original motion_prompts count:", len(muse_data.get("motion_prompts", {})))
print("EP01 shots to merge:", len(ep01_shots))

motion_prompts = muse_data.get("motion_prompts", {})

# Clean existing non-ep01 prompts
cleaned_prompts = {}
for k, v in motion_prompts.items():
    if k.lower().startswith("ep01_"):
        continue
    # For non-ep01 shots that might violate test_f5_03 (outdoor scenes using raw studio portraits)
    if any(sc in k for sc in ["scene04", "scene05", "scene06"]):
        if isinstance(v, dict) and "character_asset_ref" in v:
            ref = v["character_asset_ref"]
            if "characters" in ref and "keyframes" not in ref and "backgrounds" not in ref:
                v["character_asset_ref"] = ref.replace("04_Assets/characters/", "04_Assets/keyframes/characters/")
    cleaned_prompts[k] = v

# Merge all 188 EP01 shots
for shot_id, shot_info in ep01_shots.items():
    cleaned_prompts[shot_id] = shot_info

# Guard all shots across cleaned_prompts for off-screen / distant / VO dialogue
for shot_id, shot_info in cleaned_prompts.items():
    if not isinstance(shot_info, dict):
        continue
    audio_text = shot_info.get("audio_prompt", "")
    motion_text = shot_info.get("motion_prompt", "")
    full_text = json.dumps(shot_info, ensure_ascii=False).lower()

    if "từ xa" in audio_text.lower() or "ngoài khung" in audio_text.lower() or "v.o." in audio_text.lower() or "từ xa" in full_text or "ngoài khung" in full_text or "v.o." in full_text:
        has_closed = any(w in motion_text.lower() for w in ["khép chặt", "khép môi", "lips closed", "không mấp máy"])
        if not has_closed:
            guard_clause = " [KHÓA KHẨU HÌNH BẮT BUỘC / LIPS CLOSED]: Đôi môi nhân vật trong khung hình khép chặt tự nhiên khi nghe tiếng gọi từ xa hoặc giọng dẫn chuyện V.O. (lips closed), tuyệt đối không mấp máy."
            shot_info["motion_prompt"] = motion_text + guard_clause

muse_data["motion_prompts"] = cleaned_prompts
muse_data["version"] = "2.0"

with open(muse_file, "w", encoding="utf-8") as f:
    json.dump(muse_data, f, ensure_ascii=False, indent=2)

print("Saved muse_ai_video_prompts.json with", len(cleaned_prompts), "motion prompts.")
