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 check_button_1():
    sync_worker_profile()
    downloads_dir = Path.home() / "Downloads"
    existing = set(downloads_dir.glob("*.mp4"))
    
    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)
        
        thread_link = page.locator('button:has-text("Tạo video Thúy Kiều"), a:has-text("Tạo video Thúy Kiều")').first
        if thread_link.count() > 0:
            thread_link.click()
            time.sleep(3)
            
        dl_selector = 'button[aria-label*="Tải video xuống"], button[aria-label*="Download"], button:has-text("Tải video xuống")'
        buttons = page.locator(dl_selector)
        print(f"Buttons count: {buttons.count()}")
        if buttons.count() >= 2:
            print("Clicking button 0 (first button)...")
            buttons.first.scroll_into_view_if_needed()
            buttons.first.click(force=True)
            
            for _ in range(15):
                time.sleep(1)
                new_files = [f for f in downloads_dir.glob("*.mp4") if f not in existing]
                if new_files:
                    new_files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
                    if new_files[0].stat().st_size > 50000:
                        print(f"Button 0 Downloaded: {new_files[0].name} ({new_files[0].stat().st_size} bytes)")
                        break

if __name__ == "__main__":
    check_button_1()
