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

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

load_env_file() {
  local file="$1"
  [[ -f "$file" ]] || return 0

  while IFS= read -r line || [[ -n "$line" ]]; do
    line="${line#${line%%[![:space:]]*}}"
    line="${line%${line##*[![:space:]]}}"
    [[ -z "$line" ]] && continue
    [[ "$line" == \#* ]] && continue
    [[ "$line" != *=* ]] && continue

    local key="${line%%=*}"
    local val="${line#*=}"
    key="${key#${key%%[![:space:]]*}}"
    key="${key%${key##*[![:space:]]}}"
    [[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || continue

    if [[ "$val" =~ ^\".*\"$ ]]; then
      val="${val:1:${#val}-2}"
    elif [[ "$val" =~ ^\'.*\'$ ]]; then
      val="${val:1:${#val}-2}"
    fi

    if [[ -z "${!key:-}" ]]; then
      export "$key=$val"
    fi
  done < "$file"
}

usage() {
  cat <<'EOF' >&2
Usage:
  ACR_REGISTRY=... ACR_NAMESPACE=... [ACR_USERNAME=... ACR_PASSWORD=...] bash build-push-acr.sh

Required:
  ACR_REGISTRY   e.g. registry.cn-hangzhou.aliyuncs.com OR <instance>-registry.<region>.cr.aliyuncs.com
  ACR_NAMESPACE  your namespace

Optional:
  ENV_FILE       env file to load (default: ../deploy/.env if exists)
  IMAGE_REPO     default: digital-archive-frontend
  IMAGE_TAG      default: git sha or timestamp
  PKG_MANAGER    pnpm|npm (build-arg)
  NPM_REGISTRY   custom npm registry (build-arg)
  ACR_USERNAME / ACR_PASSWORD  if set, script will docker login before pushing

Compatibility:
  REPO_URL -> ACR_REGISTRY
  NAMESPACE -> ACR_NAMESPACE
EOF
}

if [[ -n "${ENV_FILE:-}" ]]; then
  load_env_file "$ENV_FILE"
else
  load_env_file "$script_dir/../deploy/.env"
fi

if [[ -z "${ACR_REGISTRY:-}" && -n "${REPO_URL:-}" ]]; then
  export ACR_REGISTRY="$REPO_URL"
fi
if [[ -z "${ACR_NAMESPACE:-}" && -n "${NAMESPACE:-}" ]]; then
  export ACR_NAMESPACE="$NAMESPACE"
fi

if [[ -z "${ACR_REGISTRY:-}" || -z "${ACR_NAMESPACE:-}" ]]; then
  echo "Missing required env: ACR_REGISTRY and/or ACR_NAMESPACE" >&2
  usage
  exit 2
fi

image_repo="${IMAGE_REPO:-digital-archive-frontend}"
image_tag="${IMAGE_TAG:-}"

if [[ -z "$image_tag" ]]; then
  if command -v git >/dev/null 2>&1; then
    image_tag="$(git -C "$script_dir" rev-parse --short HEAD 2>/dev/null || true)"
  fi
fi

if [[ -z "$image_tag" ]]; then
  image_tag="$(date +%Y%m%d%H%M%S)"
fi

image_ref="${ACR_REGISTRY}/${ACR_NAMESPACE}/${image_repo}:${image_tag}"

if [[ -n "${ACR_USERNAME:-}" && -n "${ACR_PASSWORD:-}" ]]; then
  printf '%s' "$ACR_PASSWORD" | docker login "$ACR_REGISTRY" -u "$ACR_USERNAME" --password-stdin
fi

build_args=()
if [[ -n "${PKG_MANAGER:-}" ]]; then
  build_args+=(--build-arg "PKG_MANAGER=${PKG_MANAGER}")
fi
if [[ -n "${NPM_REGISTRY:-}" ]]; then
  build_args+=(--build-arg "NPM_REGISTRY=${NPM_REGISTRY}")
fi

docker build \
  -f "$script_dir/Dockerfile" \
  -t "$image_ref" \
  "${build_args[@]}" \
  "$script_dir"

docker push "$image_ref"

echo "Pushed: $image_ref"
echo "WEB_IMAGE=$image_ref"
