#!/usr/bin/env python3
import socket
import sys
import time


def main() -> int:
    if len(sys.argv) < 3:
        print("usage: metin-wait-port <host> <port> [timeout_secs]", file=sys.stderr)
        return 2

    host = sys.argv[1]
    port = int(sys.argv[2])
    timeout_secs = float(sys.argv[3]) if len(sys.argv) > 3 else 30.0
    deadline = time.monotonic() + timeout_secs

    while time.monotonic() < deadline:
        try:
            with socket.create_connection((host, port), timeout=0.5):
                return 0
        except OSError:
            time.sleep(0.2)

    print(f"Timed out waiting for {host}:{port}", file=sys.stderr)
    return 1


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