#!/usr/bin/env bash
# Normalize catalog data, align Magento attributes/options, and prime
# per-connection Magento projection cache without pushing products/images.
#
# Usage:
#   ./scripts/normalize_and_prime_magento_connections.sh
#   BROCHURE_FOLDER=/home/.../brochure ./scripts/normalize_and_prime_magento_connections.sh
#   MAGENTO_CONNECTION_IDS="1 4" ./scripts/normalize_and_prime_magento_connections.sh
#
# Intended for systemd ExecStart, for example:
#   ExecStart=/bin/bash /home/homesurplus/PlytixMage/scripts/normalize_and_prime_magento_connections.sh
#
# Env:
#   APP_ROOT                PlytixMage root (default: script parent/..)
#   VENV_DIR                Virtualenv directory (default: $APP_ROOT/.venv)
#   PYTHON                  Python interpreter override (default: $VENV_DIR/bin/python, fallback: python)
#   ALEMBIC                 Alembic executable override (default: $VENV_DIR/bin/alembic, fallback: alembic)
#   LOG_DIR                 Log directory (default: $APP_ROOT/logs)
#   BROCHURE_FOLDER         Folder passed to seed_collection_filter_profiles
#   MAGENTO_CONNECTION_IDS  Space-separated Magento native connection ids (default: "1 4")
#   RUN_ALEMBIC             1 = run alembic upgrade head first (default: 1)
#   RUN_SEED_FILTERS        1 = seed brochure-driven collection filter profiles (default: 1)
#   RUN_IMAGE_PUSH          1 = append outbound image-only pushes after priming (default: 0)
#   SHOPIFY_CONNECTION_IDS  Space-separated Shopify compat/native connection ids for image push
#   IMAGE_PUSH_LIMIT        SKU limit used for auto-selected image pushes (default: 10000)
#   IMAGE_PUSH_WAIT         1 = wait for Magento image-only queue completion (default: 1)
#   IMAGE_PUSH_FORCE        1 = force Shopify image push even if hash unchanged (default: 1)
#
# Notes:
# - This script uses channel_full_publish as the repo-supported equivalent of
#   "rebuild projection cache" for a specific Magento connection.
# - Normal operation does not push Magento products or images.
# - Optional image-only push phase can be enabled via RUN_IMAGE_PUSH=1.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_ROOT="$(cd "${APP_ROOT:-$SCRIPT_DIR/..}" && pwd)"
VENV_DIR="${VENV_DIR:-$APP_ROOT/.venv}"
if [[ -z "${PYTHON:-}" ]]; then
  if [[ -x "$VENV_DIR/bin/python" ]]; then
    PYTHON="$VENV_DIR/bin/python"
  else
    PYTHON="python"
  fi
else
  PYTHON="$PYTHON"
fi
if [[ -z "${ALEMBIC:-}" ]]; then
  if [[ -x "$VENV_DIR/bin/alembic" ]]; then
    ALEMBIC="$VENV_DIR/bin/alembic"
  else
    ALEMBIC="alembic"
  fi
else
  ALEMBIC="$ALEMBIC"
fi
LOG_DIR="${LOG_DIR:-$APP_ROOT/logs}"
BROCHURE_FOLDER="${BROCHURE_FOLDER:-../plytixftp.dev.piesol.com/brochure}"
MAGENTO_CONNECTION_IDS="${MAGENTO_CONNECTION_IDS:-1 4}"
RUN_ALEMBIC="${RUN_ALEMBIC:-1}"
RUN_SEED_FILTERS="${RUN_SEED_FILTERS:-1}"
RUN_IMAGE_PUSH="${RUN_IMAGE_PUSH:-0}"
SHOPIFY_CONNECTION_IDS="${SHOPIFY_CONNECTION_IDS:-}"
IMAGE_PUSH_LIMIT="${IMAGE_PUSH_LIMIT:-10000}"
IMAGE_PUSH_WAIT="${IMAGE_PUSH_WAIT:-1}"
IMAGE_PUSH_FORCE="${IMAGE_PUSH_FORCE:-1}"

mkdir -p "$LOG_DIR"
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
LOG_FILE="$LOG_DIR/normalize_prime_magento_${STAMP}.log"
STATUS_FILE="$LOG_DIR/normalize_prime_magento_latest.status"

cd "$APP_ROOT"
export PYTHONUNBUFFERED=1

exec > >(tee -a "$LOG_FILE") 2>&1

echo "=== normalize + align Magento attributes/options + prime projection cache ==="
echo "started_utc=$STAMP"
echo "app_root=$APP_ROOT"
echo "venv_dir=$VENV_DIR"
echo "brochure_folder=$BROCHURE_FOLDER"
echo "magento_connection_ids=$MAGENTO_CONNECTION_IDS"
echo "run_alembic=$RUN_ALEMBIC"
echo "run_seed_filters=$RUN_SEED_FILTERS"
echo "run_image_push=$RUN_IMAGE_PUSH"
echo "shopify_connection_ids=$SHOPIFY_CONNECTION_IDS"
echo "image_push_limit=$IMAGE_PUSH_LIMIT"
echo "image_push_wait=$IMAGE_PUSH_WAIT"
echo "image_push_force=$IMAGE_PUSH_FORCE"
echo "log_file=$LOG_FILE"
echo "python=$PYTHON ($("$PYTHON" --version 2>&1 || true))"
echo "alembic=$ALEMBIC ($("$ALEMBIC" --version 2>&1 || true))"
echo

fail() {
  local step="$1"
  local code="$2"
  echo "FAILED step=$step exit=$code"
  echo "failed:$step:$code:$(date -u +%Y%m%dT%H%M%SZ)" >"$STATUS_FILE"
  exit "$code"
}

run_step() {
  local name="$1"
  shift
  echo
  echo "------------------------------------------------------------"
  echo "STEP: $name"
  echo "CMD: $*"
  echo "started: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
  echo "------------------------------------------------------------"
  if "$@"; then
    echo "OK: $name ($(date -u +%Y-%m-%dT%H:%M:%SZ))"
  else
    local code=$?
    fail "$name" "$code"
  fi
}

run_brochure_seed() {
  local -a cmd=(
    "$PYTHON" -m app.jobs.seed_collection_filter_profiles
    --folder "$BROCHURE_FOLDER"
    --apply
  )
  run_step "seed_collection_filter_profiles" "${cmd[@]}"
}

run_connection_steps() {
  local connection_id="$1"

  run_step "magento_attribute_preflight_mark_provision_conn_${connection_id}" \
    "$PYTHON" -m app.jobs.magento_attribute_preflight \
      --connection-id "$connection_id" \
      --mark-missing-create-new \
      --provision

  run_step "magento_baseline_sync_conn_${connection_id}" \
    "$PYTHON" -m app.jobs.magento_baseline_sync \
      --connection-id "$connection_id" \
      --force

  run_step "ensure_magento_spec_attributes_conn_${connection_id}" \
    "$PYTHON" -m app.jobs.ensure_magento_spec_attributes \
      --connection-id "$connection_id" \
      --apply \
      --provision-missing

  run_step "magento_baseline_sync_post_spec_conn_${connection_id}" \
    "$PYTHON" -m app.jobs.magento_baseline_sync \
      --connection-id "$connection_id" \
      --force

  run_step "magento_attribute_preflight_verify_conn_${connection_id}" \
    "$PYTHON" -m app.jobs.magento_attribute_preflight \
      --connection-id "$connection_id"

  run_step "prime_projection_cache_conn_${connection_id}" \
    "$PYTHON" -m app.jobs.channel_full_publish \
      --apply \
      --channel magento \
      --magento-connection-id "$connection_id" \
      --skip-pull \
      --skip-taxonomy \
      --skip-products \
      --skip-images

  run_step "inspect_projection_cache_conn_${connection_id}" \
    "$PYTHON" -m app.jobs.inspect_channel_projection \
      --channel magento \
      --connection-id "$connection_id"
}

run_magento_image_push() {
  local connection_id="$1"
  local -a cmd=(
    "$PYTHON" -m app.jobs.push_channel_sample
    --channels magento
    --magento-connection-id "$connection_id"
    --images-only
    --limit "$IMAGE_PUSH_LIMIT"
    --no-dry-run
  )
  if [[ "$IMAGE_PUSH_WAIT" == "1" ]]; then
    cmd+=(--wait)
  fi
  run_step "push_magento_images_conn_${connection_id}" "${cmd[@]}"
}

run_shopify_image_push() {
  local connection_id="$1"
  local -a cmd=(
    "$PYTHON" -m app.jobs.shopify_push_images
    --connection-id "$connection_id"
    --limit "$IMAGE_PUSH_LIMIT"
    --no-dry-run
  )
  if [[ "$IMAGE_PUSH_FORCE" == "1" ]]; then
    cmd+=(--force)
  fi
  run_step "push_shopify_images_conn_${connection_id}" "${cmd[@]}"
}

if [[ "$RUN_ALEMBIC" == "1" ]]; then
  run_step "alembic_upgrade_head" "$ALEMBIC" upgrade head
fi

run_step "cleanup_polluted_collection_filter_profiles" \
  "$PYTHON" -m app.jobs.cleanup_polluted_collection_filter_profiles --apply

if [[ "$RUN_SEED_FILTERS" == "1" ]]; then
  run_brochure_seed
fi

run_step "backfill_collection_filter_attributes" \
  "$PYTHON" -m app.jobs.backfill_collection_filter_attributes --apply

run_step "impute_collection_filter_attributes" \
  "$PYTHON" -m app.jobs.impute_collection_filter_attributes --apply

run_step "normalize_location_availability_codes" \
  "$PYTHON" -m app.jobs.normalize_location_availability_codes --apply

TAXONOMY_CMD=(
  "$PYTHON" -m app.jobs.sync_master_taxonomy_pipeline
  --apply
  --skip-product-push
)
for connection_id in $MAGENTO_CONNECTION_IDS; do
  TAXONOMY_CMD+=(--magento-connection-id "$connection_id")
done
run_step "sync_master_taxonomy_pipeline" "${TAXONOMY_CMD[@]}"

for connection_id in $MAGENTO_CONNECTION_IDS; do
  run_connection_steps "$connection_id"
done

if [[ "$RUN_IMAGE_PUSH" == "1" ]]; then
  for connection_id in $MAGENTO_CONNECTION_IDS; do
    run_magento_image_push "$connection_id"
  done
  for connection_id in $SHOPIFY_CONNECTION_IDS; do
    run_shopify_image_push "$connection_id"
  done
fi

echo
echo "=== completed successfully $(date -u +%Y-%m-%dT%H:%M:%SZ) ==="
echo "ok:$(date -u +%Y%m%dT%H%M%SZ)" >"$STATUS_FILE"
echo "status_file=$STATUS_FILE"
echo "log_file=$LOG_FILE"
