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 DEFAULT_PROFILE

def inspect_download_mechanism():
    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(5)
        
        # Check React Fiber / Props on the download button and parent video container
        info = page.evaluate("""() => {
            const btn = document.querySelector('button[data-pel-click="media_download"]');
            if (!btn) return { error: "No download button found" };
            
            // Look for closest article or message container
            const container = btn.closest('[data-message-author], [role="article"], div[class*="message"], div[class*="bubble"]') || btn.parentElement;
            
            // Check all attributes and React keys
            const getReactProps = (el) => {
                const key = Object.keys(el).find(k => k.startsWith('__reactFiber') || k.startsWith('__reactProps'));
                return key ? el[key] : null;
            };
            
            // Search for video URLs in document
            const videoEls = Array.from(document.querySelectorAll('video')).map(v => ({
                src: v.src,
                currentSrc: v.currentSrc,
                videoWidth: v.videoWidth,
                videoHeight: v.videoHeight,
                duration: v.duration,
                error: v.error ? v.error.message || v.error.code : null
            }));
            
            // Search for links or blob references
            const links = Array.from(document.querySelectorAll('a[download], a[href*="blob"], a[href*="video"]')).map(a => ({
                href: a.href,
                download: a.download
            }));
            
            return {
                btnTag: btn.tagName,
                btnDisabled: btn.disabled,
                btnAriaDisabled: btn.getAttribute('aria-disabled'),
                videoEls: videoEls,
                links: links,
                containerHTML: container ? container.outerHTML.slice(0, 500) : null
            };
        }""")
        
        print("Inspection result:", info)

if __name__ == '__main__':
    inspect_download_mechanism()
