import sys
import time
from pathlib import Path
import shutil

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 download_ready_video():
    sync_worker_profile()
    downloads_dir = Path.home() / "Downloads"
    target_video = Path("04_Assets/videos/ep01_scene01_shot01_10s.mp4").resolve()
    
    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(4)
        
        # Check download button
        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:
            before_files = set(downloads_dir.glob("*.mp4"))
            print("Clicking download button...")
            dl_btn.click()
            time.sleep(5)
            
            after_files = set(downloads_dir.glob("*.mp4")) - before_files
            if not after_files:
                recent = sorted(downloads_dir.glob("*.mp4"), key=lambda f: f.stat().st_mtime, reverse=True)
                if recent and time.time() - recent[0].stat().st_mtime < 60:
                    after_files = [recent[0]]
                    
            if after_files:
                dl_file = list(after_files)[0]
                print(f"Downloaded: {dl_file.name} ({dl_file.stat().st_size} bytes)")
                shutil.copy2(dl_file, target_video)
                print(f"Saved to: {target_video}")
            else:
                print("No file downloaded to Downloads directory.")
        else:
            print("No download button found.")

if __name__ == "__main__":
    download_ready_video()
