import sys, 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 trace_download_click():
    sync_worker_profile()
    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        
        page.on("request", lambda r: print(f"[REQ] {r.method} {r.url}"))
        page.on("response", lambda r: print(f"[RESP {r.status}] {r.url}"))
        page.on("download", lambda d: print(f"[DOWNLOAD EVENT] url={d.url}, filename={d.suggested_filename}"))
        page.on("console", lambda m: print(f"[CONSOLE {m.type}] {m.text}"))
        
        page.goto("https://muse.ai", wait_until="domcontentloaded", timeout=30000)
        time.sleep(4)
        
        dl_btns = page.locator('button[aria-label="Tải video xuống"]').all()
        print(f"DL buttons found: {len(dl_btns)}")
        if dl_btns:
            btn = dl_btns[-1]
            print("Clicking DL button...")
            try:
                with page.expect_download(timeout=10000) as dl_info:
                    btn.click(force=True)
                dl = dl_info.value
                out_path = Path("04_Assets/trace_downloaded_video.mp4").resolve()
                dl.save_as(str(out_path))
                print(f"✓ Successfully downloaded via expect_download to: {out_path} ({out_path.stat().st_size} bytes)")
            except Exception as e:
                print(f"expect_download exception: {e}")
                
        time.sleep(3)

if __name__ == '__main__':
    trace_download_click()
