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

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

profile = Path.home() / 'AntigravityProfiles' / 'phu2234_worker'
lock_file = profile / "parent.lock"
if lock_file.exists():
    try: lock_file.unlink()
    except Exception: pass

with InvisiblePlaywright(profile_dir=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)
    page.wait_for_timeout(4000)
    print("Page URL:", page.url)
    print("Page Title:", page.title())

    # Take screenshot
    screen_path = Path("04_Assets/scene07_shot04_screen.png")
    page.screenshot(path=str(screen_path))
    print(f"Saved screenshot to {screen_path}")

    dl_selector = 'button[aria-label*="Tải video xuống"], button[aria-label*="Download"]'
    dl_btns = page.locator(dl_selector)
    print(f"DL buttons found: {dl_btns.count()}")

    for i in range(dl_btns.count()):
        btn = dl_btns.nth(i)
        print(f"Btn {i}: aria-label={btn.get_attribute('aria-label')}, visible={btn.is_visible()}")

    if dl_btns.count() > 0:
        downloads_dir = Path.home() / "Downloads"
        existing = set(downloads_dir.glob("*.mp4"))
        
        # Click with expect_download or standard click
        print("Clicking latest DL button...")
        try:
            with page.expect_download(timeout=10000) as download_info:
                dl_btns.last.click(force=True)
            download = download_info.value
            target = Path("04_Assets/videos/ep01_scene07_shot04_10s_v1.mp4")
            download.save_as(str(target))
            print(f"✓ Downloaded via expect_download: {target.name} ({target.stat().st_size} bytes)")
        except Exception as e:
            print("expect_download error:", e)
            # Fallback to polling Downloads folder
            for _ in range(10):
                time.sleep(1.5)
                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:
                        target = Path("04_Assets/videos/ep01_scene07_shot04_10s_v1.mp4")
                        shutil.move(str(new_files[0]), str(target))
                        print(f"✓ Moved from Downloads: {target.name}")
                        break
