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 trace_send():
    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        
        req_logs = []
        def on_req(r):
            print(f"[REQ] {r.method} {r.url}")
            try:
                if r.post_data:
                    print(f"      DATA: {r.post_data[:300]}")
            except Exception: pass
            
        def on_resp(r):
            print(f"[RESP {r.status}] {r.url}")
            try:
                t = r.text()
                print(f"      RESP BODY: {t[:300]}")
            except Exception: pass

        page.on("request", on_req)
        page.on("response", on_resp)
        page.on("console", lambda m: print(f"[CONSOLE {m.type}] {m.text}"))
        page.on("requestfailed", lambda r: print(f"[FAILED] {r.method} {r.url} -> {r.failure}"))
        page.on("websocket", lambda ws: print(f"[WS] {ws.url}"))

        print("Navigating to https://muse.ai ...")
        page.goto("https://muse.ai", wait_until="domcontentloaded", timeout=30000)
        time.sleep(4)
        
        chat_box = page.locator('textarea, [placeholder*="Nhắn tin"], [placeholder*="Message"], [role="textbox"]').first
        chat_box.click()
        time.sleep(1)
        chat_box.fill("Chào Muse, kiểm tra kết nối")
        time.sleep(1)
        
        print("\n--- CLICKING SEND BUTTON NOW ---")
        send_btn = page.locator('button[data-pel-click="chat_send_message"], button[aria-label="Gửi"], button[aria-label*="Gửi"]').first
        if send_btn.count() > 0 and send_btn.is_visible():
            send_btn.click()
        else:
            chat_box.press("Enter")
            
        time.sleep(10)
        page.screenshot(path="04_Assets/trace_send_after.png")

if __name__ == '__main__':
    trace_send()
