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 inspect_click_behavior():
    sync_worker_profile()
    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        
        # Intercept console messages
        page.on("console", lambda msg: print(f"[CONSOLE] {msg.text}"))
        
        page.goto("https://muse.ai", wait_until="domcontentloaded", timeout=30000)
        time.sleep(4)
        
        res = page.evaluate("""() => {
            let captured = [];
            const origCreate = document.createElement.bind(document);
            document.createElement = function(tag) {
                const el = origCreate(tag);
                if (tag.toLowerCase() === 'a') {
                    const origClick = el.click.bind(el);
                    el.click = function() {
                        captured.push({ href: el.href, download: el.download });
                        return origClick();
                    };
                }
                return el;
            };
            
            const btn = document.querySelector('button[aria-label="Tải video xuống"]');
            if (btn) {
                btn.click();
            }
            return { foundBtn: !!btn, captured: captured };
        }""")
        
        print("Result:", res)
        time.sleep(3)
        
        # Check again after 3s
        res2 = page.evaluate("() => window.__captured || []")
        print("Captured anchors:", res2)

if __name__ == "__main__":
    inspect_click_behavior()
