#!/bin/bash

nexus_load_env_file() {
  local env_file="$1"
  if [ ! -f "$env_file" ]; then
    return 0
  fi

  while IFS= read -r line; do
    [[ "$line" =~ ^[[:space:]]*# ]] && continue
    [[ -z "${line// }" ]] && continue

    if [[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; then
      local key="${line%%=*}"
      if [ -z "${!key+x}" ]; then
        export "$line"
      fi
    fi
  done < "$env_file"
}

nexus_normalize_url() {
  local raw="$1"
  raw="${raw%"${raw##*[![:space:]]}"}"
  raw="${raw#"${raw%%[![:space:]]*}"}"
  printf '%s\n' "${raw%/}"
}

nexus_url_host() {
  local raw
  raw="$(nexus_normalize_url "$1")"
  raw="${raw#*://}"
  raw="${raw%%/*}"
  printf '%s\n' "${raw%%:*}"
}

nexus_url_port() {
  local normalized host_port
  normalized="$(nexus_normalize_url "$1")"
  host_port="${normalized#*://}"
  host_port="${host_port%%/*}"

  if [[ "$host_port" == *:* ]]; then
    printf '%s\n' "${host_port##*:}"
    return 0
  fi

  if [[ "$normalized" == https://* ]]; then
    printf '443\n'
    return 0
  fi

  printf '80\n'
}

nexus_export_runtime_env() {
  local project_root="${1:-$(pwd)}"

  # .env.test first: nexus_load_env_file uses first-wins semantics, so the
  # more-specific test file must be loaded before the general .env defaults.
  # This lets E2E overrides (ports 43001/4173) take priority over dev values.
  nexus_load_env_file "$project_root/.env.test"
  if [ -n "${NEXUS_USE_LOCAL+x}" ]; then
    nexus_load_env_file "$project_root/.env.local"
  fi
  nexus_load_env_file "$project_root/.env"

  export FRONTEND_URL="$(nexus_normalize_url "${FRONTEND_URL:-${PLAYWRIGHT_BASE_URL:-${REACT_APP_FRONTEND_URL:-http://127.0.0.1:5173}}}")"
  export API_BASE_URL="$(nexus_normalize_url "${API_BASE_URL:-${PLAYWRIGHT_API_URL:-${NEXUSCRM_URL:-${REACT_APP_BACKEND_URL:-http://127.0.0.1:3001}}}}")"

  export PLAYWRIGHT_BASE_URL="$(nexus_normalize_url "${PLAYWRIGHT_BASE_URL:-$FRONTEND_URL}")"
  export PLAYWRIGHT_API_URL="$(nexus_normalize_url "${PLAYWRIGHT_API_URL:-$API_BASE_URL}")"
  export NEXUSCRM_URL="$(nexus_normalize_url "${NEXUSCRM_URL:-$API_BASE_URL}")"
  export VITE_BACKEND_PROXY_TARGET="$(nexus_normalize_url "${VITE_BACKEND_PROXY_TARGET:-$API_BASE_URL}")"

  # Compatibility shim for production-mode frontend builds; browser routing
  # should still use the same-origin proxy target above.
  export REACT_APP_BACKEND_URL="$(nexus_normalize_url "${REACT_APP_BACKEND_URL:-$API_BASE_URL}")"
  export REACT_APP_FRONTEND_URL="$(nexus_normalize_url "${REACT_APP_FRONTEND_URL:-$FRONTEND_URL}")"

  export FRONTEND_HOST="${FRONTEND_HOST:-${PLAYWRIGHT_FRONTEND_HOST:-$(nexus_url_host "$FRONTEND_URL")}}"
  export FRONTEND_PORT="${FRONTEND_PORT:-${PLAYWRIGHT_FRONTEND_PORT:-$(nexus_url_port "$FRONTEND_URL")}}"
  export API_HOST="${API_HOST:-$(nexus_url_host "$API_BASE_URL")}"
  export API_PORT="${API_PORT:-$(nexus_url_port "$API_BASE_URL")}"
  export PORT="${PORT:-$API_PORT}"

  local storage_provider
  storage_provider="$(printf '%s' "${FILE_STORAGE_PROVIDER:-}" | tr '[:upper:]' '[:lower:]')"
  if [ "$storage_provider" = "s3" ] && nexus_should_fallback_file_storage; then
    export FILE_STORAGE_PROVIDER="filesystem"
    export FILE_STORAGE_ROOT="${FILE_STORAGE_ROOT:-data/object-storage}"
    echo "⚠️  FILE_STORAGE_PROVIDER=s3 but no AWS credentials detected for local runtime; falling back to filesystem storage at ${FILE_STORAGE_ROOT}" >&2
  fi
}

nexus_should_fallback_file_storage() {
  local api_host
  api_host="${API_HOST:-$(nexus_url_host "${API_BASE_URL:-http://127.0.0.1:3001}")}"

  case "$api_host" in
    localhost|127.0.0.1)
      ;;
    *)
      return 1
      ;;
  esac

  if [ -n "${FILE_STORAGE_ACCESS_KEY_ID:-}" ] && [ -n "${FILE_STORAGE_SECRET_ACCESS_KEY:-}" ]; then
    return 1
  fi

  if [ -n "${AWS_ACCESS_KEY_ID:-}" ] && [ -n "${AWS_SECRET_ACCESS_KEY:-}" ]; then
    return 1
  fi

  if [ -n "${AWS_PROFILE:-}" ]; then
    return 1
  fi

  return 0
}
