import sys
import time
from pathlib import Path

sys.path.insert(0, '05_Production_Pipeline')
if sys.platform == 'win32':
    sys.stdout.reconfigure(encoding='utf-8')
from invisible_playwright import InvisiblePlaywright

pdir = Path.home() / 'AntigravityProfiles' / 'phu2234_worker'
with InvisiblePlaywright(profile_dir=pdir, headless=True) as ctx:
    page = ctx.pages[0] if ctx.pages else ctx.new_page()
    page.goto('https://muse.ai/thread/new', wait_until='domcontentloaded', timeout=25000)
    time.sleep(3)
    
    # Click vào Shot 01 thread
    for b in page.locator('button').all():
        txt = b.inner_text().strip()
        if 'làng quê 1980' in txt or '10:03' in txt:
            b.click()
            break
            
    time.sleep(3)
    
    # Inspect all elements in thread
    html = page.content()
    # Search for download or mp4 or muse cdn urls
    import re
    mp4_links = re.findall(r'https?://[^\s"\'<>]+\.mp4[^\s"\'<>]*', html)
    print('MP4 links found in HTML:', mp4_links)
    
    buttons = []
    for btn in page.locator('button, [role="button"]').all():
        aria = btn.get_attribute('aria-label') or ''
        text = btn.inner_text().strip().replace('\n', ' ')
        title = btn.get_attribute('title') or ''
        data_pel = btn.get_attribute('data-pel-click') or ''
        if any(w in (aria + text + title + data_pel).lower() for w in ['tải', 'download', 'media', 'xem', 'save', 'lưu']):
            buttons.append(f"tag={btn.evaluate('el => el.tagName')} | text='{text}' | aria='{aria}' | title='{title}' | data_pel='{data_pel}'")
            
    print('Candidate Download Buttons:')
    for b in buttons:
        print('  -', b)
