import sys
import time
from pathlib import Path
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

profile_dir = Path("content/browser_profiles/chrome_mirsixabcf2").resolve()
extension_dir = Path("extension").resolve()

with sync_playwright() as p:
    context = p.chromium.launch_persistent_context(
        user_data_dir=str(profile_dir),
        channel="chrome",
        headless=True,
        user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36",
        args=[
            f"--load-extension={extension_dir}",
            "--disable-blink-features=AutomationControlled",
            "--window-size=1600,1000"
        ]
    )
    page = context.pages[0] if context.pages else context.new_page()

    print("[1/2] Mở tab Bình luận trên YouTube Studio...")
    page.goto("https://studio.youtube.com/channel/UClZnv08RDTD4vgLOw1jmOuA/comments/inbox", wait_until="domcontentloaded")
    time.sleep(6)
    page.screenshot(path="downloads/studio_comments_inbox.png")
    print("✓ Đã chụp ảnh tab Bình luận: downloads/studio_comments_inbox.png")

    # Đọc danh sách bình luận trên giao diện Studio
    threads = page.locator("ytcp-comment-thread, ytcp-comment").all()
    print(f"Số lượng comment threads tìm thấy trên Studio: {len(threads)}")
    for t in threads:
        try:
            author = t.locator("#author-name").inner_text().strip()
            text = t.locator("#content-text").inner_text().strip()
            video_title = t.locator(".video-title, #video-title").inner_text().strip() if t.locator(".video-title, #video-title").is_visible() else ""
            print(f"  • [{author}] trên video '{video_title}': {text}")
        except Exception:
            pass

    # Kiểm tra tab Giữ lại để xem xét (Held for review)
    print("\n[2/2] Kiểm tra tab Bình luận chờ duyệt...")
    page.goto("https://studio.youtube.com/channel/UClZnv08RDTD4vgLOw1jmOuA/comments/held_for_review", wait_until="domcontentloaded")
    time.sleep(5)
    page.screenshot(path="downloads/studio_comments_held.png")
    print("✓ Đã chụp ảnh bình luận chờ duyệt: downloads/studio_comments_held.png")

    context.close()
