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

SHORT_ID = "l3lwPorZ70A"
PLAYLIST_URL = "https://www.youtube.com/playlist?list=PLZBnH5iYlu-w"

COMMENT_TEXT = f"""🎬 Watch the full 8-part 4K documentary series in order:
👉 {PLAYLIST_URL}

⚔️ Tonight at 19:00 VN: Episode 4 Premiere (Tayson Strikes Back)!
Subscribe to @thehistoricalvault-z9 for weekly epic battles."""

def main():
    print("=" * 65)
    print(f"🚀 KIỂM TRA VÀ GẮN BÌNH LUẬN TRÊN SHORT 933 VIEWS ({SHORT_ID})")
    print("=" * 65)

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

    try:
        # Lấy danh sách bình luận
        com_req = youtube.commentThreads().list(
            part="snippet",
            videoId=SHORT_ID,
            maxResults=20
        )
        com_resp = com_req.execute()
        items = com_resp.get("items", [])
        print(f"Số lượng bình luận hiện có: {len(items)}")

        already_commented = False
        for it in items:
            c_text = it["snippet"]["topLevelComment"]["snippet"]["textDisplay"]
            author = it["snippet"]["topLevelComment"]["snippet"]["authorDisplayName"]
            print(f"  • [{author}]: {c_text[:60]}...")
            if PLAYLIST_URL in c_text or "The Historical Vault" in author:
                already_commented = True
                print("  -> Đã có bình luận của kênh trên Short này.")
                break

        if not already_commented:
            print("\n-> Đang đăng bình luận điều hướng về Playlist...")
            insert_body = {
                "snippet": {
                    "videoId": SHORT_ID,
                    "topLevelComment": {
                        "snippet": {
                            "textOriginal": COMMENT_TEXT
                        }
                    }
                }
            }
            ins_req = youtube.commentThreads().insert(
                part="snippet",
                body=insert_body
            )
            ins_resp = ins_req.execute()
            print(f"✓ Đã đăng bình luận thành công! ID: {ins_resp['id']}")
    except Exception as e:
        print(f"[-] Lỗi thao tác bình luận: {e}")

if __name__ == "__main__":
    main()
