import sys
sys.stdout.reconfigure(encoding='utf-8')
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials

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

try:
    res = yt.commentThreads().list(
        part='snippet,replies',
        allThreadsRelatedToChannelId='UClZnv08RDTD4vgLOw1jmOuA',
        maxResults=50
    ).execute()
    print(f"Total threads related to channel: {len(res.get('items', []))}")
    for it in res.get('items', []):
        top = it['snippet']['topLevelComment']['snippet']
        print(f"[{top['publishedAt']}] {top['authorDisplayName']} on video {it['snippet'].get('videoId')}: {top['textOriginal']}")
        if 'replies' in it:
            for r in it['replies']['comments']:
                rs = r['snippet']
                print(f"    ↳ [{rs['publishedAt']}] {rs['authorDisplayName']}: {rs['textOriginal']}")
except Exception as e:
    print(f"Error: {e}")
