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 check_ws_and_connection():
    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 OPEN] {ws.url}"))
        page.on("console", lambda m: print(f"[CONSOLE {m.type}] {m.text}"))
        page.on("requestfailed", lambda r: print(f"[REQ FAILED] {r.method} {r.url} -> {r.failure}"))
        page.on("response", lambda r: print(f"[RESP {r.status}] {r.url}") if any(k in r.url for k in ["hatch", "token", "chat", "thread", "ws", "socket"]) else None)
        
        print("Navigating to https://muse.ai/thread/new ...")
        page.goto("https://muse.ai/thread/new", wait_until="networkidle", timeout=30000)
        time.sleep(5)
        
        # Check what network activity is ongoing
        print("Waiting 15 seconds to observe connection state...")
        time.sleep(15)
        
        page.screenshot(path="04_Assets/ws_check.png")
        # Check if the right panel still says "Đang kết nối..."
        text_content = page.content()
        if "Đang kết nối" in text_content:
            print("Detected: 'Đang kết nối' is still showing on page!")
        else:
            print("Status: Connected!")

if __name__ == '__main__':
    check_ws_and_connection()
