import sys
import time
import json
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(
        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",
        viewport={"width": 1600, "height": 1000}
    )

    # 1. Main Channel Page
    print("[1/3] Quét trang chủ kênh...")
    page.goto("https://www.youtube.com/@thehistoricalvault-z9", wait_until="networkidle")
    time.sleep(3)
    page.screenshot(path="downloads/public_channel_home.png")
    
    header_text = page.locator("#channel-header, #meta, ytd-channel-meta-renderer").all_inner_texts()
    print("Header info:\n" + "\n".join([h.strip() for h in header_text if h.strip()]))

    # 2. Videos Tab
    print("\n[2/3] Quét tab Videos...")
    page.goto("https://www.youtube.com/@thehistoricalvault-z9/videos", wait_until="networkidle")
    time.sleep(3)
    page.screenshot(path="downloads/public_channel_videos.png")

    videos = page.locator("ytd-rich-item-renderer, ytd-grid-video-renderer").all()
    print(f"Tìm thấy {len(videos)} video trên tab Videos:")
    for v in videos:
        try:
            t = v.locator("#video-title, #video-title-link").inner_text().strip()
            meta = v.locator("#metadata-line").inner_text().strip().replace("\n", " | ")
            print(f"  • {t} [{meta}]")
        except Exception:
            pass

    # 3. Shorts Tab
    print("\n[3/3] Quét tab Shorts...")
    page.goto("https://www.youtube.com/@thehistoricalvault-z9/shorts", wait_until="networkidle")
    time.sleep(3)
    page.screenshot(path="downloads/public_channel_shorts.png")

    shorts = page.locator("ytd-rich-item-renderer").all()
    print(f"Tìm thấy {len(shorts)} shorts trên tab Shorts:")
    for s in shorts:
        try:
            st = s.locator("#video-title").inner_text().strip()
            sm = s.locator("#metadata-line").inner_text().strip().replace("\n", " | ")
            print(f"  • {st} [{sm}]")
        except Exception:
            pass

    browser.close()
    print("\n✓ Hoàn tất quét dữ liệu công khai!")
