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

PAGES = [
    ("Episode 1", "https://www.youtube.com/watch?v=DT202N1I4-A"),
    ("Episode 2", "https://www.youtube.com/watch?v=FKPhXdwFbII"),
    ("Episode 3", "https://www.youtube.com/watch?v=gZ40mP451Rc"),
    ("Short 1", "https://www.youtube.com/shorts/l3lwPorZ70A")
]

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page(viewport={"width": 1600, "height": 1200})

    for name, url in PAGES:
        print(f"\n==========================================")
        print(f"🔍 Kiểm tra bình luận trực tiếp trên {name}: {url}")
        page.goto(url, wait_until="domcontentloaded")
        time.sleep(3)

        if "shorts" in url:
            # Click nút comment trên Shorts
            c_btn = page.locator("#comments-button, ytd-button-renderer:has(#comments-button), [aria-label*='bình luận'], [aria-label*='comment']").first
            if c_btn.is_visible():
                c_btn.click()
                time.sleep(2)
        else:
            # Cuộn xuống để load comment section
            page.mouse.wheel(0, 800)
            time.sleep(2)
            page.mouse.wheel(0, 800)
            time.sleep(2)

        comments = page.locator("#content-text, ytd-comment-view-model #content-text").all_inner_texts()
        authors = page.locator("#author-text, ytd-comment-view-model #author-text").all_inner_texts()
        print(f"Số lượng bình luận hiển thị: {len(comments)}")
        for a, c in zip(authors, comments):
            print(f"  • [{a.strip()}]: {c.strip()}")

    browser.close()
