import sys
import time
import shutil
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'
downloads_dir = Path.home() / "Downloads"
target_video = Path(r"C:\Projects\KieuStory\04_Assets\videos\prologue_shot02_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. Click vào activity item trên cùng bên phải
    act = page.locator('text="Tạo cảnh quay ông cháu hoàng hôn"').first
    if act.count() == 0:
        act = page.locator('div[class*="text-subheadline-medium"]:has-text("ông cháu")').first
        
    print("Found activity item:", act.count() > 0)
    if act.count() > 0:
        act.click()
        time.sleep(3)
        
    page.screenshot(path=r"C:\Projects\KieuStory\04_Assets\temp_downloads\shot02_modal.png")
    
    # 2. Tìm thẻ file card MP4
    card = page.locator('span[data-testid*="hatch-chat-file-card"]').first
    print("Found MP4 card:", card.count() > 0)
    
    opt_btn = card.locator('button[aria-label="Lựa chọn khác"]').first
    print("Found options button:", opt_btn.count() > 0)
    
    click_t = time.time()
    if opt_btn.count() > 0:
        opt_btn.click()
        time.sleep(1)
        
        dl_btn = page.locator('div[role="menu"] *:has-text("Tải xuống")').last
        print("Found download button in menu:", dl_btn.count() > 0)
        dl_btn.click()
        print("Clicked 'Tải xuống', waiting for file in Downloads...")
        time.sleep(3)
    else:
        # Thử click vào card trực tiếp
        card.click()
        time.sleep(3)
        
    # 3. Quét thư mục Downloads
    success = False
    for i in range(12):
        time.sleep(1.5)
        recent = [f for f in downloads_dir.glob("*.mp4") if f.stat().st_mtime >= click_t - 5.0]
        if recent and recent[0].stat().st_size > 50000:
            shutil.copy2(str(recent[0]), str(target_video))
            print(f"🎉 THÀNH CÔNG: Đã tải và lưu {target_video.name} ({target_video.stat().st_size} bytes)!")
            success = True
            break
            
    if not success:
        print("[!] Chưa tải được video từ modal, kiểm tra screenshot shot02_modal.png")
