import sys
import time
from playwright.sync_api import sync_playwright

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

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page(viewport={"width": 1600, "height": 1200})
    page.goto("https://www.youtube.com/@thehistoricalvault-z9/posts", wait_until="networkidle")
    time.sleep(3)

    # Click vào nút bình luận trên bài đăng nếu có
    comment_btn = page.locator("#reply-button, ytd-button-renderer:has(#reply-button), [aria-label*='comment'], [aria-label*='bình luận'], ytd-backstage-post-thread-renderer #reply-button-end").all()
    print(f"Tìm thấy {len(comment_btn)} nút bình luận.")
    for b in comment_btn:
        print("Nút:", b.inner_text().strip())

    # Lấy link bài post
    post_links = page.locator("a[href*='/post/']").all()
    print(f"Links bài post: {[l.get_attribute('href') for l in post_links]}")

    if post_links:
        post_url = "https://www.youtube.com" + post_links[0].get_attribute("href")
        print(f"\nĐi tới trang riêng bài post: {post_url}")
        page.goto(post_url, wait_until="networkidle")
        time.sleep(4)
        page.screenshot(path="downloads/community_post_detail.png")
        
        # Đọc bình luận dưới bài post
        comments = page.locator("#content-text").all_inner_texts()
        print(f"Bình luận tìm thấy trên bài post ({len(comments)}):")
        for c in comments:
            print(f"  • {c.strip()}")

    browser.close()
