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_and_click():
    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)
        
        # Find all elements in sidebar that look like threads
        items = page.locator('div:has-text("Tạo video"), li:has-text("Tạo video"), button:has-text("Tạo video"), [class*="item"]:has-text("Tạo video")')
        print("Matching items count:", items.count())
        for i in range(items.count()):
            el = items.nth(i)
            print(f"Item {i}: text='{el.inner_text().strip()[:50]}', tag={el.evaluate('el => el.tagName')}")
            
        # Also look for threads by selector
        thread_btns = page.locator('button:has-text("Tạo video"), div[role="button"]:has-text("Tạo video"), a:has-text("Tạo video")')
        print("Thread clickable buttons:", thread_btns.count())
        for i in range(thread_btns.count()):
            print(f"  btn {i}: {thread_btns.nth(i).inner_text().strip()[:50]}")
            
        # Click on the unread one (with blue dot or "hoàng hôn")
        hoang_hon = page.locator('text="Tạo video Thuy Kieu ho"').first
        if hoang_hon.count() > 0:
            print("Clicking on 'Tạo video Thuy Kieu ho'...")
            hoang_hon.click()
            time.sleep(4)
            page.screenshot(path="04_Assets/thread_hoang_hon.png")
            print(f"URL after click: {page.url}")
            
            # Check messages in this thread
            msgs = page.locator('[class*="message"], [data-pel*="message"], [role="presentation"]')
            print("Messages count:", msgs.count())
            body_text = page.locator('main, [class*="chat-container"], [class*="content"]').inner_text()
            print("Main text excerpt:\n", "\n".join(body_text.splitlines()[-15:]))
            
            # Check video & download button
            dls = page.locator('button[aria-label*="Tải video xuống"], button[data-pel="media_download"]')
            print(f"Download buttons in thread: {dls.count()}")
            videos = page.locator('video')
            print(f"Videos in thread: {videos.count()}")
            for vi in range(videos.count()):
                v = videos.nth(vi)
                print(f"  v {vi}: src={v.get_attribute('src')}, readyState={v.evaluate('el => el.readyState')}")

if __name__ == '__main__':
    inspect_and_click()
