#!/usr/bin/env bash
# wait_for_http — polling HTTP hasta 200/2xx o timeout

wait_for_http() {
    local url="${1:-}"
    local timeout="${2:-30}"
    local interval="${3:-1}"

    # Validar dependencia
    if ! command -v curl &>/dev/null; then
        echo "wait_for_http: curl no encontrado" >&2
        return 5
    fi

    # Validar URL
    if [[ -z "$url" || ( "$url" != http://* && "$url" != https://* ) ]]; then
        echo "wait_for_http: URL invalida — debe empezar por http:// o https://" >&2
        return 2
    fi

    local start
    start=$(date +%s)
    local last_code="none"

    while true; do
        local now
        now=$(date +%s)
        local elapsed=$(( now - start ))

        if (( elapsed >= timeout )); then
            echo "TIMEOUT $url after ${timeout}s, last code: $last_code" >&2
            return 1
        fi

        local code
        code=$(curl -fsS -o /dev/null -w "%{http_code}" --max-time 5 "$url" 2>/dev/null || true)
        last_code="${code:-000}"

        echo ". waiting $url code=$last_code elapsed=${elapsed}s" >&2

        # 2xx => OK
        if [[ "$last_code" =~ ^2[0-9]{2}$ ]]; then
            local finish
            finish=$(date +%s)
            local total=$(( finish - start ))
            echo "OK $url (${total}s)"
            return 0
        fi

        sleep "$interval"
    done
}
