import sys
import time
from pathlib import Path
from invisible_playwright import InvisiblePlaywright

if sys.platform == "win32":
    sys.stdout.reconfigure(encoding="utf-8", line_buffering=True)
    sys.stderr.reconfigure(encoding="utf-8", line_buffering=True)

pdir = Path.home() / 'AntigravityProfiles' / 'phu2234_worker'
target_video = Path(r"C:\Projects\KieuStory\04_Assets\videos\prologue_shot01_10s_v1.mp4")

with InvisiblePlaywright(profile_dir=pdir, headless=True) as ctx:
    page = ctx.pages[0] if ctx.pages else ctx.new_page()
    page.goto('https://muse.ai', wait_until='networkidle', timeout=30000)
    time.sleep(3)
    
    # 1. Mở modal từ activity
    act = page.locator('text="Tạo video điện ảnh 10s thập niên 1980"').first
    if act.count() > 0:
        act.click()
        time.sleep(3)
        
    # 2. Tìm thẻ MP4 card
    card = page.locator('span[title*="media-generation-toan-canh-thap-nien-1980"]').first
    print("Found MP4 title:", card.count() > 0)
    
    # Tìm nút 'Lựa chọn khác' trong card
    # Parent chứa nút aria-label="Lựa chọn khác"
    parent_card = page.locator('span[data-testid*="hatch-chat-file-card"]').first
    print("Found parent card with data-testid:", parent_card.count() > 0)
    
    opt_btn = parent_card.locator('button[aria-label="Lựa chọn khác"]').first
    print("Found 'Lựa chọn khác' button:", opt_btn.count() > 0)
    
    if opt_btn.count() > 0:
        opt_btn.click()
        time.sleep(1)
        
        # Xem menu
        menu = page.locator('div[role="menu"]')
        print("Menu text:\n", menu.inner_text())
        
        # Bắt sự kiện download khi click Tải xuống
        download_btn = menu.locator('*:has-text("Tải xuống")').last
        print("Found Tải xuống button:", download_btn.count() > 0)
        
        if download_btn.count() > 0:
            print("Listening for download event...")
            with page.expect_download(timeout=30000) as download_info:
                download_btn.click()
            download = download_info.value
            download.save_as(str(target_video))
            print(f"🎉 THÀNH CÔNG RỰC RỠ: Đã tải file về {target_video} ({target_video.stat().st_size} bytes)!")
    else:
        print("Không thấy nút lựa chọn khác, thử click trực tiếp vào thẻ...")
        with page.expect_download(timeout=15000) as download_info:
            parent_card.click()
        download = download_info.value
        download.save_as(str(target_video))
        print(f"🎉 THÀNH CÔNG: Đã tải {target_video} ({target_video.stat().st_size} bytes)!")

