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,1200"
        ]
    )
    page = context.pages[0] if context.pages else context.new_page()
    page.goto("https://studio.youtube.com/video/O-8w_ONx3as/edit", wait_until="domcontentloaded")
    time.sleep(5)
    
    # Click "HIỆN THÊM"
    show_more = page.locator("#toggle-button, ytcp-button:has-text('HIỆN THÊM'), ytcp-button:has-text('Hiện thêm')").first
    if show_more.is_visible():
        show_more.click()
        time.sleep(1)
        print("✓ Đã bấm 'Hiện thêm'")
    
    # Try scrolling down using mouse wheel
    for _ in range(5):
        page.mouse.wheel(0, 500)
        time.sleep(0.5)

    time.sleep(2)
    page.screenshot(path="downloads/ep4_scrolled_mouse.png")
    print("✓ Đã chụp ảnh cuộn chuột: downloads/ep4_scrolled_mouse.png")

    # Look for "Nội dung đã qua chỉnh sửa" or radio button
    yes_radio = page.locator("tp-yt-paper-radio-button:has-text('Có'), ytcp-radio-button:has-text('Có')").first
    if yes_radio.is_visible():
        checked = yes_radio.get_attribute("aria-checked")
        print(f"Trạng thái nút Có: {checked}")
        if checked != "true":
            yes_radio.click()
            print("✓ Đã click nút 'Có'")
            time.sleep(1)
            save_btn = page.locator("#save, ytcp-button#save-button, ytcp-button:has-text('LƯU'), ytcp-button:has-text('Lưu')").first
            if save_btn.is_visible() and not save_btn.get_attribute("disabled"):
                save_btn.click()
                time.sleep(3)
                print("✓ Đã lưu thành công!")
    else:
        print("[-] Không thấy nút 'Có' trực tiếp, kiểm tra thêm trong trang")

    context.close()
