import os
import sys
import json
from youtube_uploader import get_youtube_service

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

# Danh sách các bản nháp 720p cần xóa trên YouTube Studio
DRAFTS_TO_DELETE = {
    "2": "FKPhXdwFbII",
    "3": "gZ40mP451Rc",
    "4": "QKQtThVT0r4",
    "5": "lygtPzWC7Ig",
    "6": "UOaAm7zVOV4"
}

def delete_draft_videos():
    youtube = get_youtube_service()
    print("=== BẮT ĐẦU XÓA CÁC BẢN NHÁP 720P TRÊN YOUTUBE STUDIO ===")
    print("LƯU Ý: Tuyệt đối không xóa bất kỳ file nào trong ổ cứng máy local!")
    
    deleted_ids = []
    
    for ep, vid in DRAFTS_TO_DELETE.items():
        print(f"\n[*] Kiểm tra Tập {ep} (ID: {vid}) trên YouTube...")
        try:
            res = youtube.videos().list(part="snippet,status", id=vid).execute()
            items = res.get("items", [])
            if items:
                title = items[0]["snippet"]["title"]
                status = items[0]["status"]["privacyStatus"]
                print(f" -> Tìm thấy video: '{title}' | Trạng thái: {status}")
                
                # Tiến hành xóa trên YouTube qua API
                youtube.videos().delete(id=vid).execute()
                print(f" -> [ĐÃ XÓA TRÊN YOUTUBE] Video ID {vid} của Tập {ep} đã bị xóa vĩnh viễn khỏi kênh.")
                deleted_ids.append(ep)
            else:
                print(f" -> Video ID {vid} không tồn tại trên kênh (có thể đã xóa trước đó).")
                deleted_ids.append(ep)
        except Exception as e:
            print(f" -> [Lỗi khi xóa ID {vid}]: {e}")
            
    # Cập nhật lại file uploaded_episodes.json
    state_file = "uploaded_episodes.json"
    if os.path.exists(state_file):
        try:
            with open(state_file, "r", encoding="utf-8") as f:
                data = json.load(f)
            for ep in deleted_ids:
                if ep in data:
                    del data[ep]
            with open(state_file, "w", encoding="utf-8") as f:
                json.dump(data, f, indent=2, ensure_ascii=False)
            print("\n[OK] Đã cập nhật lại file uploaded_episodes.json (loại bỏ các tập 2-6).")
        except Exception as e:
            print(f"[-] Lỗi cập nhật state file: {e}")

if __name__ == "__main__":
    delete_draft_videos()
