# HCL (Terraform >= 0.12.20)
locals {
  combined_cardinal_directions = {
    northeast = "ne",
    northwest = "nw",
    southeast = "se",
    southwest = "sw",
  }

  aws_region_array = split("-", lower(var.aws_region_name))
  aws_region_code = join("", [for i, v in local.aws_region_array :
    alltrue([
      i == 0,
      i == length(local.aws_region_array) - 1,
      (i == 1 && v == "gov")
    ]) ? v : try(local.combined_cardinal_directions[v], substr(v, 0, 1))
  ])
}

# Shell (Bash)
: "${AWS_REGION:=us-east-1}" # Default region
AWS_REGION_CODE=""
mapfile -d - -t PARTS <<<"${AWS_REGION,,}"
for ((i=0; i<${#PARTS[@]}; i++)); do
  PART="${PARTS[$i]//[[:space:]]}"
  if [[ $i -eq 0 || $i+1 -eq ${#PARTS[@]} || ($i -eq 1 && $PART == gov) ]]; then
    AWS_REGION_CODE+="$PART"
  else
    case $PART in
      northeast)  PART="ne";;
      northwest)  PART="nw";;
      southeast)  PART="se";;
      southwest)  PART="sw";;
      *)          PART="${PART:0:1}";;
    esac
    AWS_REGION_CODE+="$PART"
  fi
done

# Groovy
def getAwsRegionCodeFromName(String awsRegionName) {
  assert awsRegionName.getClass() == String
  assert !awsRegionName.isEmpty()
  assert !awsRegionName.isAllWhitespace()

  List awsRegionArray = awsRegionName.toLowerCase().split('-')
  assert awsRegionArray.size() == 3 || awsRegionArray.size() == 4

  Map<String,String> combinedCardinalDirections = [
    northeast: 'ne',
    northwest: 'nw',
    southeast: 'se',
    southwest: 'sw',
  ]

  List awsRegionCodeArray = []

  awsRegionArray.eachWithIndex { item, idx ->
    if (idx == 0 || idx == awsRegionArray.size() - 1 || (idx == 1 && item == 'gov')) {
      awsRegionCodeArray.add(item)
    } else {
      awsRegionCodeArray.add(combinedCardinalDirections[item] ?: item.charAt(0))
    }
  }

  assert !awsRegionCodeArray.isEmpty()
  return awsRegionCodeArray.join()
}

# Python
COMBINED_CARDINAL_DIRECTIONS = {
    "northeast": "ne",
    "northwest": "nw",
    "southeast": "se",
    "southwest": "sw",
}

def get_aws_region_code(region_name):
    """Returns AWS region code"""
    region_code = []
    parts = region_name.split("-")
    for idx, part in enumerate(parts):
        part = part.strip()
        if idx == 0 or idx + 1 == len(parts) or (idx == 1 and part == "gov"):
            region_code.append(part)
        else:
            region_code.append(COMBINED_CARDINAL_DIRECTIONS.get(part, part[0]))
    region_code = "".join(region_code)
    return region_code