"""Issue 196: pending_response race condition.

Send play + concurrent gamestate — the play response is lost.
"""
import socket, json, threading, time

HOST = "127.0.0.1"
PORT = 60065

def send_request(method, params=None, rid=1, timeout=10):
    """Send a JSON-RPC request and return the full HTTP response."""
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(timeout)
    try:
        s.connect((HOST, PORT))
        body = json.dumps({"jsonrpc": "2.0", "method": method, "params": params or {}, "id": rid})
        buf = (
            f"POST / HTTP/1.1\r\n"
            f"Host: {HOST}:{PORT}\r\n"
            f"Content-Type: application/json\r\n"
            f"Content-Length: {len(body)}\r\n"
            f"\r\n{body}"
        )
        s.sendall(buf.encode())
        resp = b""
        while True:
            try:
                chunk = s.recv(4096)
            except socket.timeout:
                break
            if not chunk:
                break
            resp += chunk
        return resp
    except socket.timeout:
        return b""
    finally:
        s.close()


def send_async(method, params=None, rid=1, timeout=10, results=None, key=""):
    resp = send_request(method, params, rid, timeout)
    if results is not None:
        results[key] = resp


# --- Setup: start a run ---
send_request("menu")
time.sleep(0.3)
send_request("start", {"deck": "RED", "stake": "WHITE", "seed": "BUG5"})
time.sleep(0.3)
send_request("select")
time.sleep(0.1)
send_request("set", {"chips": 1000000, "money": 500})
time.sleep(0.1)

# --- Reproduction: send play, then immediately send gamestate ---
results = {}
t1 = threading.Thread(target=send_async, args=("play", {"cards": [0, 1, 2, 3, 4]}, 1, 30, results, "play"))
t2 = threading.Thread(target=send_async, args=("gamestate", {}, 2, 10, results, "gamestate"))

t1.start()
time.sleep(0.1)  # 100ms gap — play is still blocking
t2.start()

t1.join()
t2.join()

play_resp = results.get("play", b"")
gs_resp = results.get("gamestate", b"")

print(f"PLAY response: {len(play_resp)} bytes")
print(f"GAMESTATE response: {len(gs_resp)} bytes")

if len(play_resp) == 0:
    print("BUG CONFIRMED: play response is empty (lost due to race)")
else:
    # Check if the response has a JSON body
    parts = play_resp.split(b"\r\n\r\n", 1)
    if len(parts) > 1:
        body = parts[1][:100]
        print(f"Play body: {body}")
    else:
        print(f"Play raw: {play_resp[:100]}")
