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

# Run from the deployed api directory, or pass the absolute script path.
# Download once, preview both markets, then import each market separately.
# PHP_BIN may point to the hosting account's PHP 8.3+ binary.
cd "$(dirname "$0")/.."
KALEMAT_PHP="${PHP_BIN:-php}"
KALEMAT_DIR="$(pwd)/storage/app/imports/kalemat"
KALEMAT_SOURCE="$KALEMAT_DIR/products.json"
KALEMAT_ACTION="${1:-}"

if ! "$KALEMAT_PHP" -r 'exit(PHP_VERSION_ID >= 80300 ? 0 : 1);'; then
  echo 'PHP 8.3+ is required. Set PHP_BIN to the correct CLI binary.' >&2
  exit 1
fi

if [[ "$KALEMAT_ACTION" == download ]]; then
  mkdir -p "$KALEMAT_DIR"
  KALEMAT_PARTIAL="$(mktemp "$KALEMAT_DIR/products.download.XXXXXX")"
  trap 'rm -f "$KALEMAT_PARTIAL"' EXIT
  curl --fail --location --compressed --connect-timeout 20 --max-time 600 \
    --retry 2 --retry-delay 3 'https://kalemat.com/ar/test_smartsolns' --output "$KALEMAT_PARTIAL"
  "$KALEMAT_PHP" -d memory_limit=1024M -r '
    $json = file_get_contents($argv[1]);
    if (!json_validate($json) || !str_starts_with(ltrim($json), "[")) {
        fwrite(STDERR, "Incomplete or invalid product JSON; previous snapshot preserved.\n");
        exit(1);
    }
  ' "$KALEMAT_PARTIAL"
  mv "$KALEMAT_PARTIAL" "$KALEMAT_SOURCE"
  echo "Snapshot ready: $KALEMAT_SOURCE"
  exit 0
fi

if [[ "$KALEMAT_ACTION" != 1 && "$KALEMAT_ACTION" != 19 ]]; then
  echo 'Usage: bash scripts/kalemat-json-import.sh download' >&2
  echo '       bash scripts/kalemat-json-import.sh {1|19} [--dry-run] [--store=CODE] [--skip-images]' >&2
  exit 1
fi
shift
if [[ ! -s "$KALEMAT_SOURCE" ]]; then
  echo 'Run the download command first; both stores must use the same snapshot.' >&2
  exit 1
fi

"$KALEMAT_PHP" -d memory_limit=1024M artisan catalog:import-kalemat-json \
  --tenant=kalemat --country="$KALEMAT_ACTION" --source-file="$KALEMAT_SOURCE" --with-static \
  --report="$KALEMAT_DIR/report-$KALEMAT_ACTION-$(date -u +%Y%m%dT%H%M%SZ).json" "$@"
