#!/usr/bin/env bash
# Import SEO + prefix colors, then fast-push selected Magento attributes for all CSV SKUs.
#
# This script avoids the older collection product sync path for shopping_* because some
# Magento connections now require select option IDs for shopping_collection/shopping_l1/shopping_l2.
# Instead it uses the normal Magento attribute queue path, which resolves labels to option IDs.
#
# Default behavior:
# 1) Import SEO CSV into master catalog
# 2) Import prefix color CSV into master catalog (Kitchen Cabinets only)
# 3) Read distinct SKUs from the SEO CSV
# 4) Queue a fast Magento attribute push for each connection
#
# Dry run:
#   DRY_RUN=1 bash scripts/apply_seo_color_and_fast_magento_push.sh
#
# Live:
#   bash scripts/apply_seo_color_and_fast_magento_push.sh
#
# Server example:
#   SEO_CSV=/home2/devpiesol/plytixftp.dev.piesol.com/HS-SKUS-SEO-Optimized-FINAL-v3.csv \
#   COLOR_CSV=/home2/devpiesol/plytixftp.dev.piesol.com/SKU-Prefix-Color-Reference-3.csv \
#   bash scripts/apply_seo_color_and_fast_magento_push.sh
#
# Env:
#   APP_ROOT                  PlytixMage root (default: script parent/..)
#   VENV_DIR                  Virtualenv directory (default: $APP_ROOT/.venv)
#   PYTHON                    Python interpreter override
#   LOG_DIR                   Log directory (default: $APP_ROOT/logs)
#   SEO_CSV                   Required path to SEO CSV
#   COLOR_CSV                 Required path to prefix-color CSV
#   MAGENTO_CONNECTION_IDS    Connection order (default: "4 1")
#   DRY_RUN                   1 = preview only (default: 0)
#   RUN_WORKER                1 = run queue worker in-process while waiting (default: 1)
#   WAIT                      1 = wait for each Magento queue (default: 1)
#   WAIT_TIMEOUT              Queue wait timeout seconds (default: 21600)
#   FAIL_ON_WAIT_TIMEOUT      1 = fail service if queue wait times out (default: 0)
#   CATEGORY_L1               Color import category limit (default: "Kitchen Cabinets")
#   USE_LOCK                  1 = flock to avoid double-run (default: 1)
#   PUSH_FIELDS               Space-separated Magento fields to push
#
# Notes:
#   - The SEO import command applies when --dry-run is absent.
#   - The color import command applies when --apply is used.
#   - Magento push uses sync_options_from_master=True so shopping_* and color_finish select
#     values can be provisioned/resolved before PUT.

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="python3"
  fi
fi

LOG_DIR="${LOG_DIR:-$APP_ROOT/logs}"
SEO_CSV="${SEO_CSV:-}"
COLOR_CSV="${COLOR_CSV:-}"
MAGENTO_CONNECTION_IDS="${MAGENTO_CONNECTION_IDS:-4 1}"
DRY_RUN="${DRY_RUN:-0}"
RUN_WORKER="${RUN_WORKER:-1}"
WAIT="${WAIT:-1}"
WAIT_TIMEOUT="${WAIT_TIMEOUT:-21600}"
FAIL_ON_WAIT_TIMEOUT="${FAIL_ON_WAIT_TIMEOUT:-0}"
CATEGORY_L1="${CATEGORY_L1:-Kitchen Cabinets}"
USE_LOCK="${USE_LOCK:-1}"
PUSH_FIELDS="${PUSH_FIELDS:-name description meta_title meta_description meta_keywords url_key color_finish shopping_collection shopping_l1 shopping_l2}"

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

cd "$APP_ROOT"
export PYTHONUNBUFFERED=1

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

echo "=== apply seo + color + fast magento push ==="
echo "started_utc=$STAMP"
echo "app_root=$APP_ROOT"
echo "python=$PYTHON ($("$PYTHON" --version 2>&1 || true))"
echo "seo_csv=$SEO_CSV"
echo "color_csv=$COLOR_CSV"
echo "magento_connections=$MAGENTO_CONNECTION_IDS"
echo "dry_run=$DRY_RUN"
echo "run_worker=$RUN_WORKER wait=$WAIT wait_timeout=$WAIT_TIMEOUT"
echo "fail_on_wait_timeout=$FAIL_ON_WAIT_TIMEOUT"
echo "category_l1=$CATEGORY_L1"
echo "push_fields=$PUSH_FIELDS"
echo "log_file=$LOG_FILE"
echo

if [[ -z "$SEO_CSV" ]]; then
  echo "SEO_CSV is required" >&2
  exit 1
fi
if [[ -z "$COLOR_CSV" ]]; then
  echo "COLOR_CSV is required" >&2
  exit 1
fi
if [[ ! -f "$SEO_CSV" ]]; then
  echo "SEO CSV not found: $SEO_CSV" >&2
  exit 1
fi
if [[ ! -f "$COLOR_CSV" ]]; then
  echo "Color CSV not found: $COLOR_CSV" >&2
  exit 1
fi

main() {
  local seo_args=()
  local color_args=()
  if [[ "$DRY_RUN" == "1" ]]; then
    seo_args+=(--dry-run)
    color_args+=(--dry-run)
  else
    color_args+=(--apply)
  fi

  echo "--- step 1: seo import ---"
  "$PYTHON" -m app.jobs.import_product_seo \
    --file "$SEO_CSV" \
    "${seo_args[@]}"
  echo

  echo "--- step 2: color import ---"
  "$PYTHON" -m app.jobs.import_prefix_colors \
    --file "$COLOR_CSV" \
    --category-l1 "$CATEGORY_L1" \
    "${color_args[@]}"
  echo

  echo "--- step 3: fast magento push for csv skus ---"
  PY_SEO_CSV="$SEO_CSV" \
  PY_MAGENTO_CONNECTION_IDS="$MAGENTO_CONNECTION_IDS" \
  PY_DRY_RUN="$DRY_RUN" \
  PY_RUN_WORKER="$RUN_WORKER" \
  PY_WAIT="$WAIT" \
  PY_WAIT_TIMEOUT="$WAIT_TIMEOUT" \
  PY_FAIL_ON_WAIT_TIMEOUT="$FAIL_ON_WAIT_TIMEOUT" \
  PY_PUSH_FIELDS="$PUSH_FIELDS" \
  "$PYTHON" - <<'PY'
import csv
import json
import os

from app.jobs.push_magento_attributes import enqueue_magento_attribute_push

seo_csv = os.environ["PY_SEO_CSV"]
connection_ids = [int(x) for x in os.environ.get("PY_MAGENTO_CONNECTION_IDS", "").split() if x.strip()]
dry_run = os.environ.get("PY_DRY_RUN", "0") == "1"
run_worker = os.environ.get("PY_RUN_WORKER", "1") == "1"
wait = os.environ.get("PY_WAIT", "1") == "1"
wait_timeout = int(os.environ.get("PY_WAIT_TIMEOUT", "21600"))
fail_on_wait_timeout = os.environ.get("PY_FAIL_ON_WAIT_TIMEOUT", "0") == "1"
field_codes = [x.strip() for x in os.environ.get("PY_PUSH_FIELDS", "").split() if x.strip()]

seen = set()
skus = []
with open(seo_csv, newline="", encoding="utf-8-sig") as handle:
    for row in csv.DictReader(handle):
        sku = str(row.get("SKU") or "").strip()
        if not sku or sku in seen:
            continue
        seen.add(sku)
        skus.append(sku)

if not skus:
    raise SystemExit("No SKUs found in SEO CSV")

summary = {
    "status": "ok",
    "dry_run": dry_run,
    "sku_count": len(skus),
    "field_codes": field_codes,
    "connections": [],
    "warnings": [],
}

for connection_id in connection_ids:
    try:
        result = enqueue_magento_attribute_push(
            field_codes=field_codes,
            skus=skus,
            filters=None,
            dry_run=dry_run,
            connection_id=connection_id,
            wait=wait,
            run_worker=run_worker,
            wait_timeout=wait_timeout,
            sync_options_from_master=True,
        )
    except TimeoutError as exc:
        warning = {
            "connection_id": connection_id,
            "warning": "wait_timeout",
            "message": str(exc),
        }
        summary["warnings"].append(warning)
        summary["connections"].append(warning)
        if fail_on_wait_timeout:
            raise
        summary["status"] = "partial"
        continue
    summary["connections"].append(
        {
            "connection_id": connection_id,
            "status": result.get("status"),
            "queue_id": result.get("queue_id"),
            "label": result.get("label"),
            "sku_count": result.get("sku_count"),
            "matched_filter_sku_count": result.get("matched_filter_sku_count"),
            "field_selection": result.get("field_selection"),
            "wait_result": {
                "job_status": result.get("job_status"),
                "completed_at": result.get("completed_at"),
                "failed_count": result.get("failed_count"),
                "processed_count": result.get("processed_count"),
            } if wait else None,
            "raw_result": result,
        }
    )

print(json.dumps(summary, indent=2, default=str))
PY

  printf 'status=ok\nfinished_utc=%s\nlog_file=%s\n' "$(date -u +%Y%m%dT%H%M%SZ)" "$LOG_FILE" > "$STATUS_FILE"
  echo
  echo "status_file=$STATUS_FILE"
  echo "done"
}

if [[ "$USE_LOCK" == "1" ]] && command -v flock >/dev/null 2>&1; then
  exec 9>"$LOCK_FILE"
  flock -n 9 || { echo "another run is already in progress: $LOCK_FILE" >&2; exit 1; }
fi

main
