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 sync_worker_profile, DEFAULT_PROFILE

def test_new_chat_connection():
    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.on('websocket', lambda ws: print(f"[WS] URL: {ws.url}"))
        
        page.goto("https://muse.ai", wait_until="domcontentloaded", timeout=30000)
        time.sleep(3)
        
        btn = page.locator('button[aria-label="Đoạn chat phụ mới"]').first
        if btn.count() > 0:
            print("Clicking 'Đoạn chat phụ mới'...")
            btn.click()
            
            for sec in range(15):
                time.sleep(1)
                text = page.locator("body").inner_text()
                has_connecting = "Đang kết nối" in text
                print(f"[{sec+1}s] 'Đang kết nối': {has_connecting}, URL: {page.url}")
                if not has_connecting and sec >= 2:
                    print("✓ WebSocket connected!")
                    break
                    
            page.screenshot(path="04_Assets/new_chat_connected_screen.png")

if __name__ == '__main__':
    test_new_chat_connection()
