#!/usr/bin/env python3
"""Hook: PreToolUse (mcp__godot__.*)
Check if Godot is listening before sending any MCP tool call.
Prevents 10s timeout hangs when Godot isn't running.
Cross-platform: works on macOS, Linux, and Windows.
"""

import json
import os
import socket
import sys


def is_port_listening(host: str, port: int) -> bool:
    """Check if a port is listening without leaving a persistent connection."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(0.5)
    try:
        result = sock.connect_ex((host, port))
        return result == 0
    except OSError:
        return False
    finally:
        sock.close()


def main():
    port = int(os.environ.get("GOLEM_PORT", "3571"))
    host = "127.0.0.1"

    if is_port_listening(host, port):
        sys.exit(0)

    # Nothing listening — block the tool call
    output = {
        "hookSpecificOutput": {
            "hookEventName": "PreToolUse",
            "additionalContext": f"Godot is not listening on port {port}. Start Godot with the Golem MCP plugin enabled, then retry.",
        }
    }
    json.dump(output, sys.stdout)
    sys.exit(2)


if __name__ == "__main__":
    main()
