"""Manual, Windows-only diagnostic: proves (or disproves) that a basic
named-pipe write/read round trip works on this machine at all, using the
exact same vendored X4_Python_Pipe_Server library x4-advisor uses for live
mode -- but with a plain Python client standing in for X4, so X4/SirNukes
are completely out of the picture.

This is NOT part of the automated test suite (it needs pywin32 and real
Windows named pipes, so it can't run in CI or on Linux) -- it's a manual
tool for narrowing down a hang in `python -m x4_advisor.live --ping-only`
that happens even before X4 gets involved in the write.

Run directly:  python tests/pipe_loopback_test.py

Expected output on success (should take well under a second):
    [server] started
    [server] connected
    [client] connected
    [client] sent PING
    [server] got: PING
    [server] sent PONG
    [client] got: PONG
    RESULT: OK -- pipe write/read round trip completed normally.

If it hangs instead (no "RESULT" line, ever), the problem is upstream of
X4 entirely -- almost certainly security software intercepting/stalling
named pipe I/O on this machine, or a Windows named-pipe permissions issue,
since this test doesn't touch X4, SirNukes, or any of x4-advisor's own
extension code.
"""

from __future__ import annotations

import os
import sys
import threading
import time

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
    "x4_advisor", "live", "vendor",
))

PIPE_NAME = "x4_advisor_loopback_test"
TIMEOUT = 10.0


def main() -> int:
    try:
        from X4_Python_Pipe_Server import Pipe_Server, Pipe_Client
    except ImportError as e:
        print(f"Could not import the vendored pipe library: {e}", file=sys.stderr)
        print("Make sure pywin32 is installed (`pip install pywin32`) and", file=sys.stderr)
        print("you're running this on Windows.", file=sys.stderr)
        return 1

    result = {"server_got": None, "client_got": None, "error": None}

    def server_thread():
        try:
            server = Pipe_Server(PIPE_NAME)
            print("[server] started")
            server.Connect()
            print("[server] connected")
            msg = server.Read()
            print(f"[server] got: {msg}")
            result["server_got"] = msg
            server.Write("PONG")
            print("[server] sent PONG")
            server.Close()
        except Exception as e:  # noqa: BLE001
            result["error"] = f"server error: {e}"

    t = threading.Thread(target=server_thread, daemon=True)
    t.start()

    # Give the server a moment to create the pipe before the client tries
    # to open it (CreateNamedPipe happens synchronously in Pipe_Server.__init__,
    # so even a short wait here is generous).
    time.sleep(1.0)

    try:
        client = Pipe_Client(PIPE_NAME)
        print("[client] connected")
        client.Write("PING")
        print("[client] sent PING")
    except Exception as e:  # noqa: BLE001
        print(f"RESULT: FAIL -- client couldn't connect/write: {e}", file=sys.stderr)
        return 1

    # Read the response with a real timeout, using a helper thread so a
    # hang here doesn't just freeze the whole script with no diagnostic
    # (same pattern as x4_advisor.live.pipe_client).
    import queue
    read_q: "queue.Queue[object]" = queue.Queue()

    def client_read():
        try:
            read_q.put(client.Read())
        except Exception as e:  # noqa: BLE001
            read_q.put(e)

    rt = threading.Thread(target=client_read, daemon=True)
    rt.start()
    try:
        got = read_q.get(timeout=TIMEOUT)
    except queue.Empty:
        print(f"RESULT: FAIL -- client.Read() did not return within {TIMEOUT:.0f}s.", file=sys.stderr)
        print("The server-side Write() likely hung too (check for a", file=sys.stderr)
        print("'[server] sent PONG' line above -- if it's missing, the", file=sys.stderr)
        print("write itself never completed).", file=sys.stderr)
        return 1

    if isinstance(got, Exception):
        print(f"RESULT: FAIL -- client read raised: {got}", file=sys.stderr)
        return 1

    print(f"[client] got: {got}")
    result["client_got"] = got

    if result["error"]:
        print(f"RESULT: FAIL -- {result['error']}", file=sys.stderr)
        return 1

    if result["server_got"] == "PING" and result["client_got"] == "PONG":
        print("RESULT: OK -- pipe write/read round trip completed normally.")
        return 0

    print(f"RESULT: FAIL -- unexpected messages: {result}", file=sys.stderr)
    return 1


if __name__ == "__main__":
    raise SystemExit(main())
