#!/usr/bin/env bash
set -euo pipefail

if [ ! -d "./evibes" ]; then
  printf "\e[31m❌  Please run this script from the project's root (where the 'evibes' directory lives).\e[0m\n"
  exit 1
fi

PURPLE="\e[38;2;121;101;209m"
RESET="\e[0m"
GRAY="\e[90m"

SOURCE="${BASH_SOURCE[0]:-$0}"
SCRIPT_DIR="$(cd "$(dirname "$SOURCE")" && pwd)"
ART_PATH="$SCRIPT_DIR/../ASCII_ART_EVIBES"

if [ ! -f "$ART_PATH" ]; then
  printf "\e[31m❌  Could not find ASCII art at %s\e[0m\n" "$ART_PATH"
  exit 1
fi

while IFS= read -r line; do
  printf "%b%s%b\n" "$PURPLE" "$line" "$RESET"
done < "$ART_PATH"

printf "\n%b                                                                       by WISELESS TEAM%b\n\n" "$GRAY" "$RESET"

ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
  printf "\e[31m.env file not found in the current directory.\e[0m\n"
  exit 1
fi

declare -A env_vars
declare -a keys

while IFS= read -r raw; do
  line="${raw%%#*}"
  line="${line%"${line##*[![:space:]]}"}"
  line="${line#"${line%%[![:space:]]*}"}"
  [ -z "$line" ] || [[ "$line" != *=* ]] && continue
  key="${line%%=*}"
  value="${line#*=}"
  if [[ "${value:0:1}" == '"' && "${value: -1}" == '"' ]] || \
     [[ "${value:0:1}" == "'" && "${value: -1}" == "'" ]]; then
    value="${value:1:-1}"
  fi
  export "$key"="$value"
  env_vars["$key"]="$value"
  keys+=("$key")
done < "$ENV_FILE"

if [ "${#keys[@]}" -gt 0 ]; then
  IFS=$'\n' sorted=($(sort <<<"${keys[*]}"))
  unset IFS
  formatted=""
  for k in "${sorted[@]}"; do
    [ -z "$formatted" ] && formatted="$k=${env_vars[$k]}" \
      || formatted="$formatted;$k=${env_vars[$k]}"
  done
  printf "%s\n" "$formatted"
fi
