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 test_new_thread_connection():
    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(3)
        
        print("[1] Opening new thread via button...")
        btn = page.locator('button[aria-label="Đoạn chat phụ mới"]').first
        btn.click()
        time.sleep(2)
        print("URL:", page.url)
        
        # Now watch for 40 seconds WITHOUT doing anything
        for i in range(8):
            time.sleep(5)
            sec = (i+1)*5
            content = page.locator('body').inner_text()
            has_connecting = "Đang kết nối" in content
            print(f"[{sec}s] Has 'Đang kết nối': {has_connecting}")
            if not has_connecting:
                print(f"🎉 Connected after {sec}s!")
                break
        page.screenshot(path="04_Assets/new_thread_idle_status.png")

if __name__ == '__main__':
    test_new_thread_connection()
