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 check_latest_thread():
    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)
        
        # Click the top chat item in "Đoạn chat phụ"
        subchats = page.locator('button:has-text("Tạo video"), a:has-text("Tạo video")')
        print(f"Subchats count: {subchats.count()}")
        if subchats.count() > 0:
            print("Clicking latest subchat:", subchats.first.inner_text())
            subchats.first.click()
            time.sleep(3)
            
        screenshot_path = Path("04_Assets/check_latest_render_state.png").resolve()
        page.screenshot(path=str(screenshot_path))
        print("Screenshot saved to:", screenshot_path)
        
        # Check download buttons
        dl_btns = page.locator('button:has-text("Tải video xuống"), button[aria-label*="Tải video xuống"]')
        print("Download buttons count:", dl_btns.count())

if __name__ == "__main__":
    check_latest_thread()
