#!/usr/bin/env bash
# Shared helpers for boot-orchestrator and customer-watchdog.
# Sourced, not executed. No set -e here — let the caller decide strictness.

whp_setting_num() {
    local key="$1" default="$2" min="$3" max="$4"
    local v=""
    if [ -f /docker/whp/settings.json ] && command -v jq >/dev/null 2>&1; then
        v="$(jq -r ".${key} // empty" /docker/whp/settings.json 2>/dev/null || echo "")"
    fi
    if ! [[ "${v}" =~ ^[0-9]+$ ]]; then echo "${default}"; return; fi
    if [ "${v}" -lt "${min}" ] || [ "${v}" -gt "${max}" ]; then echo "${default}"; return; fi
    echo "${v}"
}

whp_setting_bool() {
    local key="$1" default="$2"
    local v=""
    if [ -f /docker/whp/settings.json ] && command -v jq >/dev/null 2>&1; then
        v="$(jq -r ".${key} // empty" /docker/whp/settings.json 2>/dev/null || echo "")"
    fi
    case "${v}" in true|false) echo "${v}";; *) echo "${default}";; esac
}

# Enumerate containers by tier label only (any state). Used for tier 1-3
# (system containers managed by docker's own restart policy — they never carry
# whp.autostart=true, so filtering on that label would yield an empty set).
tier_containers() {
    local tier="$1"
    docker ps -aq --filter "label=whp.tier=${tier}" 2>/dev/null
}

# Enumerate containers by tier label AND whp.autostart=true. Used for tier 4
# (customer containers — orchestrator/watchdog source of truth).
tier_containers_autostart() {
    local tier="$1"
    docker ps -aq --filter "label=whp.tier=${tier}" --filter "label=whp.autostart=true" 2>/dev/null
}

wait_for_health() {
    local label="$1" timeout_sec="$2" healthcheck_cmd="$3"
    local elapsed=0
    while [ "$elapsed" -lt "$timeout_sec" ]; do
        if bash -c "$healthcheck_cmd" >/dev/null 2>&1; then return 0; fi
        sleep 2
        elapsed=$((elapsed + 2))
    done
    echo "TIMEOUT waiting for ${label} after ${timeout_sec}s" >&2
    return 1
}

mysql_pass_from_cnf() {
    awk -F= '/^password=/ { print $2; exit }' /root/.my.cnf 2>/dev/null
}

whp_canonical_domain() {
    local v=""
    if [ -f /docker/whp/settings.json ] && command -v jq >/dev/null 2>&1; then
        v="$(jq -r '.canonical_hosting_domain // empty' /docker/whp/settings.json 2>/dev/null || echo "")"
    fi
    if [ -z "${v}" ]; then v="anhonesthost.com"; fi
    echo "${v}"
}

log_line() {
    local level="$1" component="$2"; shift 2
    local ts; ts="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
    echo "${ts} ${level} component=${component} $*"
}
