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_video_dom():
    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.goto("https://muse.ai", wait_until="domcontentloaded", timeout=30000)
        time.sleep(4)
        
        # Check all video elements
        videos = page.locator("video")
        v_count = videos.count()
        print(f"Total <video> elements: {v_count}")
        for i in range(v_count):
            v = videos.nth(i)
            print(f"Video {i}: src={v.get_attribute('src')}, currentSrc={v.evaluate('el => el.currentSrc')}")
        
        # Check all buttons inside or near the last assistant message
        buttons = page.locator("button")
        b_count = buttons.count()
        print(f"\nTotal buttons: {b_count}")
        for i in range(b_count):
            b = buttons.nth(i)
            aria = b.get_attribute("aria-label") or ""
            text = b.inner_text().strip().replace("\n", " ")
            classes = b.get_attribute("class") or ""
            title = b.get_attribute("title") or ""
            if any(k in f"{aria} {text} {title}".lower() for k in ["tải", "down", "video", "save", "lưu", "thêm"]):
                print(f"Button {i}: text='{text}' | aria='{aria}' | title='{title}'")

        # Let's hover the last video player to see if download button appears
        if v_count > 0:
            print("\nHovering on the last video...")
            last_v = videos.last
            last_v.hover()
            time.sleep(2)
            # Recheck buttons after hover
            post_buttons = page.locator("button")
            print(f"Total buttons after hover: {post_buttons.count()}")
            for i in range(post_buttons.count()):
                b = post_buttons.nth(i)
                aria = b.get_attribute("aria-label") or ""
                text = b.inner_text().strip().replace("\n", " ")
                title = b.get_attribute("title") or ""
                if any(k in f"{aria} {text} {title}".lower() for k in ["tải", "down", "video", "save", "lưu", "thêm"]):
                    print(f"Hover Button {i}: text='{text}' | aria='{aria}' | title='{title}'")

if __name__ == "__main__":
    inspect_video_dom()
