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 analyze_client_connection():
    with InvisiblePlaywright(profile_dir=DEFAULT_PROFILE, headless=True) as ctx:
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        
        # Intercept ALL network requests and log request headers, post data, and response
        def on_request(req):
            if any(k in req.url for k in ["hatch", "chat", "thread", "message", "token", "vm"]):
                print(f"[REQ] {req.method} {req.url}")
                try:
                    if req.post_data:
                        print(f"      POST DATA: {req.post_data[:200]}")
                except Exception: pass

        def on_response(res):
            if any(k in res.url for k in ["hatch", "chat", "thread", "message", "token", "vm"]):
                print(f"[RESP {res.status}] {res.url}")
                try:
                    text = res.text()
                    print(f"      BODY: {text[:200]}")
                except Exception: pass

        page.on("request", on_request)
        page.on("response", on_response)
        
        print("Opening https://muse.ai ...")
        page.goto("https://muse.ai", wait_until="networkidle", timeout=30000)
        time.sleep(5)

if __name__ == '__main__':
    analyze_client_connection()
