#!/bin/bash

# Find the most changed dir
function most_changed_dir() {
  IFS=',' read -r -a dirs <<< "$CHANGED_DIRS"
  max_changes=0
  most_changed_dir=""
  for dir in "${dirs[@]}"; do
    echo "Analyzing changes for $dir..."
    # Count the number of line changes (additions and deletions) in the directory
    change_count=$(git diff --shortstat HEAD^ HEAD -- "$dir" | awk '{print $4 + $6}')
    echo "$dir has $change_count changes"
    if [ "$change_count" -gt "$max_changes" ]; then
      max_changes=$change_count
      most_changed_dir=$dir
      echo "Most changed directory: $most_changed_dir with $max_changes changes"
    fi
  done
}

# Export service name like sdpv2-agent-lambda-connect and also will add `infra` word
function export_service_name() {
  # Input must be like infra/agent/lambda/connect
  value=$1
  IFS='/' read -ra parts <<< "$value"
  domain="${parts[1]}"  # retrieve domain name
  resource_type="${parts[2]}"  # retrieve type of the resource like lambda, api-gw, dynamodb, sqs

  if [ "$domain" == "agent" ] || [ "$domain" == "gateway" ]; then
    if [ "$resource_type" == "api-gw-private-rest" ]; then
      changed_service_name="sdpv2-${domain}-apigw-rest-infra"
    elif [ "$resource_type" == "api-gw-public-ws" ]; then
      changed_service_name="sdpv2-${domain}-apigw-ws-infra"
    else
      service_type="${parts[3]}"  # retrieve type of the service like connect, disconnect, pusher
      if [ "$service_type" == "authorizer" ]; then
        # Cut a folder name for the authorizer lambda
        changed_service_name="sdpv2-${domain}-$resource_type-auth-infra"
      else
        changed_service_name="sdpv2-${domain}-$resource_type-${service_type}-infra"
      fi
    fi
  elif [ "$domain" == "_envcommon" ]; then
    # if changes are in _envcommon folder with common configurations
    changed_service_name="sdpv2-${domain}-${resource_type}-infra"
  elif [ "$domain" == "shared" ] || [ "$domain" == "localstack" ]; then
    # if changes are in localstack or shared resources folders
    changed_service_name="sdpv2-${domain}-infra"
  fi
}

# Call functions
most_changed_dir
# Output of the most_changed_dir function is input for export_service_name
export_service_name "$most_changed_dir"
# Print the output
echo $changed_service_name
# Export changed_service_name to Github environment variables
echo "CHANGED_SERVICE_NAME=${changed_service_name}" >> $GITHUB_ENV