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

def monitor_and_download():
    target_video = Path("04_Assets/videos/ep01_scene01_shot01_10s.mp4").resolve()
    temp_dl = Path("04_Assets/temp_downloads/invpw/shot01_muse.mp4").resolve()
    temp_dl.parent.mkdir(parents=True, exist_ok=True)
    downloads_dir = Path.home() / "Downloads"

    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)
        
        dl_selector = 'button:has-text("Tải video xuống"), button[aria-label*="Tải video xuống"], button[data-pel="media_download"], button[data-pel-click="media_download"]'
        stop_selector = 'button:has-text("Dừng"), button[aria-label*="Dừng"], button:has-text("Stop")'
        
        print("Monitoring render progress...")
        success = False
        start_time = time.time()
        
        for i in range(30): # 30 * 5s = 150s
            time.sleep(5)
            elapsed = int(time.time() - start_time)
            
            dl_count = page.locator(dl_selector).count()
            stop_count = page.locator(stop_selector).count()
            print(f"[{elapsed}s] dl_count={dl_count}, stop_count={stop_count}")
            
            if dl_count > 0:
                print(f"🎉 Phát hiện {dl_count} nút tải video! Đang bấm tải xuống...")
                btn = page.locator(dl_selector).last
                click_time = time.time()
                before_dls = {f.name: f.stat().st_mtime for f in downloads_dir.glob("*.mp4")}
                
                # 1. expect_download
                try:
                    with page.expect_download(timeout=12000) as dl_info:
                        btn.click(force=True)
                    dl = dl_info.value
                    dl.save_as(str(temp_dl))
                    if temp_dl.exists() and temp_dl.stat().st_size > 100000:
                        print(f"✓ Tải thành công qua expect_download: {temp_dl.stat().st_size} bytes")
                        success = True
                        break
                except Exception as e_dl:
                    print(f"expect_download note: {e_dl}")
                    
                # 2. Check Downloads
                if not success:
                    for _ in range(12):
                        time.sleep(1)
                        new_files = [
                            f for f in downloads_dir.glob("*.mp4")
                            if (f.name not in before_dls or f.stat().st_mtime > click_time - 1.0)
                            and f.stat().st_size > 100000
                        ]
                        if new_files:
                            new_files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
                            shutil.move(str(new_files[0]), str(temp_dl))
                            print(f"✓ Tải thành công qua Downloads: {temp_dl.stat().st_size} bytes")
                            success = True
                            break
                            
            if success:
                break
                
        page.screenshot(path="04_Assets/monitor_render_status.png")
        
        if success and temp_dl.exists():
            shutil.copy2(str(temp_dl), str(target_video))
            print(f"\n=======================================================")
            print(f"🎉 XUẤT XƯỞNG MASTER SHOT 01 THÀNH CÔNG: {target_video.name}")
            print(f"   Kích thước: {target_video.stat().st_size} bytes")
            print(f"=======================================================\n")
            
            # Extract tail frame
            from muse_invpw_driver import extract_tail_frame
            tf = extract_tail_frame(target_video, "ep01_scene01_shot01")
            print(f"✓ Tail frame extracted: {tf}")
        else:
            print("[!] Chưa hoàn thành hoặc chưa có video xuất hiện.")

if __name__ == '__main__':
    monitor_and_download()
