#!/bin/bash

# Flows
source "flows/base"
source "flows/release"
source "flows/rust"

# Vars
POSTGRES_VERSION="17"
POSTGRES_CONFIG_PATH="/opt/homebrew/opt/postgresql@${POSTGRES_VERSION}/bin/pg_config"
DEPENDENCIES=(cargo git icu4c pkg-config "postgresql@${POSTGRES_VERSION}")
CARGO_DEPENDENCIES=(cargo-pgrx==0.14.0)
GITEA_ORGANIZATION="cellular"
GITEA_REPOSITORY="jspg"
PACKAGE_NAME="jspg"

pgrx-prepare() {
  echo -e "${BLUE}Initializing pgrx...${RESET}"
  # Explicitly point to the postgresql@${POSTGRES_VERSION} pg_config, don't rely on 'which'
  local POSTGRES_CONFIG_PATH="/opt/homebrew/opt/postgresql@${POSTGRES_VERSION}/bin/pg_config"

  if [ ! -x "$POSTGRES_CONFIG_PATH" ]; then
    echo -e "${RED}Error: pg_config not found or not executable at $POSTGRES_CONFIG_PATH.${RESET}"
    echo -e "${YELLOW}Ensure postgresql@${POSTGRES_VERSION} is installed correctly via Homebrew.${RESET}"
    exit 1
  fi

  if cargo pgrx init --pg"$POSTGRES_VERSION"="$POSTGRES_CONFIG_PATH"; then
    echo -e "${GREEN}pgrx initialized successfully.${RESET}"
  else
    echo -e "${RED}Failed to initialize pgrx. Check PostgreSQL development packages are installed and $POSTGRES_CONFIG_PATH is valid.${RESET}"
    exit 1
  fi
}

build() {
  local version=$(get-version)
  echo -e "📦 ${CYAN}Building release v$version for $PACKAGE_NAME...${RESET}"

  # Define target directories
  local package_dir="./package"
  local package_source_base_dir="./target/release"

  # Define the actual base paths where package command places files within out-dir
  local package_lib_search_path="${package_source_base_dir}/opt/homebrew/lib/postgresql@17"
  local package_share_search_path="${package_source_base_dir}/opt/homebrew/share/postgresql@17/extension"

  # Clean previous package dirs
  rm -rf "${package_dir}"
  mkdir -p "${package_dir}"

  # Use cargo pgrx package to build and stage artifacts (release is default)
  if ! cargo pgrx package --pg-config "${POSTGRES_CONFIG_PATH}" --out-dir "${package_source_base_dir}"; then
      echo -e "❌ ${RED}Build failed during cargo pgrx package.${RESET}"
      exit 1
  fi

  echo -e "  ${CYAN}Copying artifacts from ${package_source_base_dir} subdirs to ${package_dir}${RESET}"

  # Find and copy the library
  local lib_path=$(find "${package_lib_search_path}" -name "${PACKAGE_NAME}.dylib" -print -quit)
  if [[ -n "$lib_path" ]]; then
      cp "$lib_path" "${package_dir}/"
      echo -e "  ✨ ${GREEN}Copied library: $(basename "$lib_path")${RESET}"
  else
      echo -e "❌ ${RED}Could not find library (${PACKAGE_NAME}.dylib) in package source dir.${RESET}"
      exit 1
  fi

  # Find and copy the control file
  local control_path=$(find "${package_share_search_path}" -name "${PACKAGE_NAME}.control" -print -quit)
  if [[ -n "$control_path" ]]; then
      cp "$control_path" "${package_dir}/"
      echo -e "  ✨ ${GREEN}Copied control file: $(basename "$control_path")${RESET}"
  else
      echo -e "❌ ${RED}Could not find control file (${PACKAGE_NAME}.control) in package source dir.${RESET}"
      exit 1
  fi

  # Find and copy the SQL file
  local sql_file_pattern="${PACKAGE_NAME}--*.sql"
  local sql_path=$(find "${package_share_search_path}" -name "${sql_file_pattern}" -print -quit)
  if [[ -n "$sql_path" ]]; then
      cp "$sql_path" "${package_dir}/"
      echo -e "  ✨ ${GREEN}Copied SQL file: $(basename "$sql_path")${RESET}"
  else
      echo -e "❌ ${RED}Could not find SQL file (${sql_file_pattern}) in package source dir.${RESET}"
      exit 1
  fi

  echo -e "✨ ${GREEN}Package artifacts created in ${package_dir}${RESET}"
}

install() {
  echo -e "🔧 ${CYAN}Installing jspg extension (dev build)...${RESET}"
  cargo pgrx install "$@" # Pass any extra args like --debug
}

test() {
  echo -e "🧪 ${CYAN}Running jspg tests...${RESET}"
  cargo pgrx test "pg${POSTGRES_VERSION}" "$@"
}

clean() {
  echo -e "🧹 ${CYAN}Cleaning build artifacts...${RESET}"
  cargo clean # Use standard cargo clean
}

usage() {
  echo -e "    install [opts] Build and install the extension locally (dev)."
  echo -e "    test [opts]    Run pgrx integration tests."
  echo -e "    clean          Remove pgrx build artifacts."
  echo -e "    build          Build release artifacts into ./package/ (called by release)."
  echo -e "    tag            Tag the current version (called by release)."
  echo -e "    package        Upload artifacts from ./package/ (called by release)."
  echo -e "    release        Perform a full release (increments patch, builds, tags, pushes, packages)."
}

case "$1" in
  prepare) base prepare; cargo-prepare; pgrx-prepare;;
  build) build;;
  install) install;;
  reinstall) reinstall;;
  test) test;;
  package) package;;
  release) create-release;;
  clean) clean;;
  *) base "$@";;
esac