import sys
import time
from pathlib import Path

sys.path.append(str(Path("05_Production_Pipeline").resolve()))
from invisible_playwright import InvisiblePlaywright
from muse_invpw_driver import sync_worker_profile, DEFAULT_PROFILE

def test_expect_download():
    sync_worker_profile()
    target_video = Path("04_Assets/videos/ep01_scene01_shot01_10s.mp4").resolve()
    target_video.parent.mkdir(parents=True, exist_ok=True)
    
    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        page.goto("https://muse.ai", wait_until="domcontentloaded", timeout=30000)
        time.sleep(3)
        
        dl_btn = page.locator('button[aria-label*="Tải video xuống"]').last
        print("Download button count:", dl_btn.count())
        if dl_btn.count() > 0:
            print("Triggering expect_download()...")
            with page.expect_download(timeout=20000) as download_info:
                dl_btn.click(force=True)
            download = download_info.value
            download.save_as(str(target_video))
            print(f"🎉 SUCCESS! Saved downloaded video to: {target_video} ({target_video.stat().st_size} bytes)")
        else:
            print("No download button found.")

if __name__ == "__main__":
    test_expect_download()
