import sys
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

CHANNEL_ID = "UClZnv08RDTD4vgLOw1jmOuA"

def main():
    print("=" * 65)
    print("🔍 QUÉT TẤT CẢ BÌNH LUẬN MỚI TRÊN KÊNH")
    print("=" * 65)

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

    req = youtube.commentThreads().list(
        part="snippet,replies",
        allThreadsRelatedToChannelId=CHANNEL_ID,
        maxResults=20,
        order="time"
    )
    resp = req.execute()
    items = resp.get("items", [])
    print(f"Tìm thấy {len(items)} bình luận mới nhất:\n")

    for idx, item in enumerate(items, 1):
        top_comment = item["snippet"]["topLevelComment"]["snippet"]
        thread_id = item["id"]
        video_id = item["snippet"].get("videoId", "N/A")
        author = top_comment.get("authorDisplayName", "Unknown")
        author_channel = top_comment.get("authorChannelId", {}).get("value", "")
        text = top_comment.get("textDisplay", "")
        published = top_comment.get("publishedAt", "")
        reply_count = item["snippet"].get("totalReplyCount", 0)

        is_owner = (author_channel == CHANNEL_ID)
        print(f"[{idx}] Video ID: {video_id} | Thread ID: {thread_id}")
        print(f"    Tác giả: {author} {'(Chủ kênh)' if is_owner else '(Khán giả)'}")
        print(f"    Thời gian: {published}")
        print(f"    Nội dung: {text}")
        print(f"    Số phản hồi: {reply_count}")
        
        # In các replies nếu có
        if "replies" in item:
            for rep in item["replies"]["comments"]:
                rep_s = rep["snippet"]
                print(f"      ↳ [{rep_s.get('authorDisplayName')}]: {rep_s.get('textDisplay')}")
        print("-" * 60)

if __name__ == "__main__":
    main()
