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

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

    # 1. Lấy Uploads Playlist ID
    ch_req = youtube.channels().list(part="contentDetails", mine=True)
    ch_res = ch_req.execute()
    uploads_pl = ch_res["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]
    print(f"Uploads Playlist ID: {uploads_pl}")

    # 2. Lấy toàn bộ video trong uploads playlist
    all_videos = []
    next_page = None
    while True:
        pl_req = youtube.playlistItems().list(
            part="snippet",
            playlistId=uploads_pl,
            maxResults=50,
            pageToken=next_page
        )
        pl_res = pl_req.execute()
        for item in pl_res.get("items", []):
            vid = item["snippet"]["resourceId"]["videoId"]
            title = item["snippet"]["title"]
            all_videos.append((vid, title))
        next_page = pl_res.get("nextPageToken")
        if not next_page:
            break

    print(f"\nTổng cộng {len(all_videos)} video trên kênh:")
    for vid, title in all_videos:
        print(f"  • {vid}: {title}")

    # 3. Quét comment trên từng video
    print("\n--- QUÉT BÌNH LUẬN TRÊN TOÀN BỘ VIDEO ---")
    found_any = False
    for vid, title in all_videos:
        try:
            c_req = youtube.commentThreads().list(part="snippet,replies", videoId=vid, maxResults=20)
            c_res = c_req.execute()
            items = c_res.get("items", [])
            if items:
                print(f"\n[VIDEO: {title}] ({vid}) - {len(items)} bình luận:")
                for it in items:
                    top = it["snippet"]["topLevelComment"]["snippet"]
                    author = top["authorDisplayName"]
                    text = top["textDisplay"]
                    cid = it["id"]
                    reply_count = it["snippet"]["totalReplyCount"]
                    print(f"   -> [{author}]: {text} (ID: {cid}, Replies: {reply_count})")
                    if "replies" in it:
                        for r in it["replies"]["comments"]:
                            rs = r["snippet"]
                            print(f"      ↳ [{rs['authorDisplayName']}]: {rs['textDisplay']}")
                found_any = True
        except Exception as e:
            # comments might be disabled or video private
            pass

    if not found_any:
        print("Không tìm thấy bình luận nào.")

if __name__ == "__main__":
    main()
