import sys
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build

if hasattr(sys.stdout, 'reconfigure'):
    try:
        sys.stdout.reconfigure(encoding='utf-8')
        sys.stderr.reconfigure(encoding='utf-8')
    except Exception:
        pass

PLAYLIST_URL = "https://www.youtube.com/playlist?list=PLZBnH5iYlu-w"
PLAYLIST_BANNER = f"🔥 BINGE THE FULL 4K SERIES IN ORDER:\n👉 {PLAYLIST_URL}\n\n"

VIDEOS = ["DT202N1I4-A", "FKPhXdwFbII", "gZ40mP451Rc", "O-8w_ONx3as"]

def main():
    print("=" * 65)
    print("🚀 ĐỒNG BỘ LINK PLAYLIST VÀO MÔ TẢ CÁC TẬP PHIM")
    print("=" * 65)

    creds = Credentials.from_authorized_user_file('token.json')
    youtube = build('youtube', 'v3', credentials=creds)

    for vid in VIDEOS:
        try:
            req = youtube.videos().list(part="snippet", id=vid)
            resp = req.execute()
            items = resp.get("items", [])
            if not items:
                continue
            
            snippet = items[0]["snippet"]
            desc = snippet["description"]
            
            if PLAYLIST_URL in desc:
                print(f"  [-] Video {vid} đã có link playlist, bỏ qua.")
                continue

            # Chèn link playlist ngay trước phần CHAPTER TIMESTAMPS hoặc PREVIOUS EPISODES
            if "⏱️ CHAPTER TIMESTAMPS:" in desc:
                parts = desc.split("⏱️ CHAPTER TIMESTAMPS:")
                new_desc = parts[0] + PLAYLIST_BANNER + "⏱️ CHAPTER TIMESTAMPS:" + parts[1]
            elif "🎬 PREVIOUS EPISODES:" in desc:
                parts = desc.split("🎬 PREVIOUS EPISODES:")
                new_desc = parts[0] + PLAYLIST_BANNER + "🎬 PREVIOUS EPISODES:" + parts[1]
            else:
                new_desc = desc + "\n\n" + PLAYLIST_BANNER

            snippet["description"] = new_desc
            update_req = youtube.videos().update(
                part="snippet",
                body={
                    "id": vid,
                    "snippet": snippet
                }
            )
            update_req.execute()
            print(f"  ✓ Đã cập nhật link Playlist vào mô tả Video {vid}!")
        except Exception as e:
            print(f"  [-] Lỗi cập nhật Video {vid}: {e}")

    print("\n✓ Hoàn tất đồng bộ mô tả!")

if __name__ == "__main__":
    main()
