#!/usr/bin/env python3
import asyncio, json, sys, websockets

async def main():
    ws = await websockets.connect("ws://127.0.0.1:6007")

    await ws.send(json.dumps({"id": "d1", "method": "ping", "params": {}}))
    r = json.loads(await asyncio.wait_for(ws.recv(), timeout=5))
    game_running = r.get("result", {}).get("game_running", False)
    status = r["status"]
    print(f"1. PING: status={status} game_running={game_running}")
    if not game_running:
        print("   Game not running! Start with F5 first.")
        await ws.close()
        return

    print("2. Sending perf_snapshot (10s timeout)...")
    await ws.send(json.dumps({"id": "d2", "method": "perf_snapshot", "params": {}}))
    try:
        while True:
            raw = await asyncio.wait_for(ws.recv(), timeout=10)
            data = json.loads(raw)
            if "event" in data:
                evt = data["event"]
                print(f"   [event: {evt}]")
                continue
            if data.get("id") == "d2":
                st = data["status"]
                print(f"   PERF: status={st}")
                if st == "ok":
                    res = data["result"]
                    print(f"   fps={res.get('fps')} draws={res.get('draw_calls')} nodes={res.get('total_nodes')}")
                else:
                    err = data.get("error", {})
                    print(f"   ERROR: [{err.get('code')}] {err.get('message')}")
                break
    except asyncio.TimeoutError:
        print("   TIMEOUT -- EngineDebugger chain is broken")
        print("   Check Godot Output for diagnostic prints.")

    await ws.close()
    print("\nDone. Check Godot Output panel for diagnostic prints.")

asyncio.run(main())
