# nordvpn_list_cities
# -------------------
# Lista las ciudades disponibles de un pais en NordVPN como array JSON.
#
# USO (sourced):
#   source nordvpn_list_cities.sh
#   nordvpn_list_cities Spain

nordvpn_list_cities() {
    local country="${1:?nordvpn_list_cities: se requiere pais como argumento}"

    if ! command -v nordvpn &>/dev/null; then
        echo '{"ok":false,"error":"nordvpn no instalado"}' >&2
        return 1
    fi

    local output
    output=$(nordvpn cities "$country" 2>&1)
    local rc=$?

    if [ $rc -ne 0 ]; then
        echo "{\"ok\":false,\"error\":$(echo "$output" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read().strip()))' 2>/dev/null || echo "\"$output\"")}"
        return 1
    fi

    echo "$output" | python3 -c '
import sys, json, re

country = "'"$country"'"
text = sys.stdin.read()
text = re.sub(r"\x1b\[[0-9;]*m", "", text)
text = re.sub(r"[\t\r]", " ", text)
cities = [c.strip().replace("_", " ") for c in re.split(r"[,\n]+", text) if c.strip() and c.strip() != "-"]
cities = [c for c in cities if len(c) > 1]
cities.sort()
print(json.dumps({"ok": True, "country": country, "count": len(cities), "cities": cities}))
'
}
