import sys
import time
import json
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_ID = "PLZBnH5iYlu-w"

EPISODES = [
    {"ep": 1, "video_id": "DT202N1I4-A", "title": "The Exiled Prince & The Foreign Alliance"},
    {"ep": 2, "video_id": "FKPhXdwFbII", "title": "50,000 Invaders: The Siamese Fleet Invades"},
    {"ep": 3, "video_id": "gZ40mP451Rc", "title": "The Fall of Gia Dinh: A Nation in Flames"},
    {"ep": 4, "video_id": "O-8w_ONx3as", "title": "Tayson Strikes Back: The Gathering Storm"},
    {"ep": 5, "video_id": "lygtPzWC7Ig", "title": "The River Trap: The Ambush at Rach Gam"},
    {"ep": 6, "video_id": "UOaAm7zVOV4", "title": "Night of Fire: The Destruction of 300 Warships"},
]

def main():
    print("=" * 65)
    print("🎬 CẬP NHẬT VIDEO VÀO OFFICIAL SERIES PLAYLIST")
    print(f"   Playlist ID: {PLAYLIST_ID}")
    print(f"   URL: https://www.youtube.com/playlist?list={PLAYLIST_ID}")
    print("=" * 65)

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

    # 1. Lấy danh sách video đã có
    existing_video_ids = set()
    for attempt in range(5):
        try:
            items_req = youtube.playlistItems().list(
                part="snippet,contentDetails",
                playlistId=PLAYLIST_ID,
                maxResults=50
            )
            items_resp = items_req.execute()
            for it in items_resp.get("items", []):
                vid = it["contentDetails"]["videoId"]
                existing_video_ids.add(vid)
            print(f"✓ Đã đọc danh sách video hiện có ({len(existing_video_ids)} video).")
            break
        except Exception as e:
            print(f"  [-] Đang đợi playlist đồng bộ (lần {attempt+1}): {e}")
            time.sleep(3)

    # 2. Thêm từng tập phim vào playlist
    for ep_info in EPISODES:
        vid = ep_info["video_id"]
        ep_num = ep_info["ep"]
        title = ep_info["title"]

        if vid in existing_video_ids:
            print(f"  [-] Tập {ep_num} ({vid}) đã có trong playlist, bỏ qua.")
            continue

        print(f"  -> Đang thêm Tập {ep_num}: {title} ({vid})...")
        item_body = {
            "snippet": {
                "playlistId": PLAYLIST_ID,
                "resourceId": {
                    "kind": "youtube#video",
                    "videoId": vid
                }
            }
        }
        added = False
        for attempt in range(3):
            try:
                add_req = youtube.playlistItems().insert(
                    part="snippet",
                    body=item_body
                )
                add_resp = add_req.execute()
                print(f"  ✓ Đã thêm Tập {ep_num} thành công! Item ID: {add_resp['id']}")
                added = True
                time.sleep(1)
                break
            except Exception as e:
                print(f"    [-] Lỗi lần {attempt+1}: {e}")
                time.sleep(2)

    # 3. Cập nhật metadata
    try:
        with open("extension/metadata.json", "r", encoding="utf-8") as f:
            meta = json.load(f)
        meta["series_playlist_id"] = PLAYLIST_ID
        meta["series_playlist_url"] = f"https://www.youtube.com/playlist?list={PLAYLIST_ID}"
        with open("extension/metadata.json", "w", encoding="utf-8") as f:
            json.dump(meta, f, indent=2, ensure_ascii=False)
        print("\n✓ Đã đồng bộ series_playlist_id vào extension/metadata.json")
    except Exception as e:
        print(f"[-] Lỗi cập nhật extension/metadata.json: {e}")

    print("\n" + "=" * 65)
    print("🎉 HOÀN TẤT THIẾT LẬP DANH SÁCH PHÁT CHÍNH THỨC!")
    print(f"   Playlist Link: https://www.youtube.com/playlist?list={PLAYLIST_ID}")
    print("=" * 65)

if __name__ == "__main__":
    main()
