#!/usr/bin/env bash
# wait_for_port — polling TCP a host:puerto hasta conexion o timeout

wait_for_port() {
    local host="$1"
    local port="$2"
    local timeout="${3:-30}"
    local interval="${4:-1}"

    # Validaciones
    if [[ -z "$host" ]]; then
        echo "wait_for_port: host vacio" >&2
        return 3
    fi
    if ! [[ "$port" =~ ^[0-9]+$ ]] || (( port < 1 || port > 65535 )); then
        echo "wait_for_port: puerto invalido '$port'" >&2
        return 2
    fi

    # Detectar metodo disponible una sola vez
    local method
    if command -v nc &>/dev/null; then
        method="nc"
    else
        method="devtcp"
    fi

    local _try_connect
    if [[ "$method" == "nc" ]]; then
        _try_connect() { nc -z -w 2 "$host" "$port" &>/dev/null; }
    else
        _try_connect() {
            (exec 3<>/dev/tcp/"$host"/"$port") &>/dev/null
        }
    fi

    local start elapsed
    start=$(date +%s)

    while true; do
        elapsed=$(( $(date +%s) - start ))
        if (( elapsed >= timeout )); then
            echo "TIMEOUT ${host}:${port} after ${timeout}s" >&2
            return 1
        fi
        echo ". waiting ${host}:${port} elapsed=${elapsed}s" >&2
        if _try_connect; then
            echo "OK ${host}:${port} (${elapsed}s)"
            return 0
        fi
        sleep "$interval"
    done
}
