#!/bin/bash
set -uo pipefail

BASE="/media/justin/syncPi/Shared/61_RW_Site/Pulled_Info"
RUNTIME_BASE="/home/justin/rw_inventory"
APPAREL_SCRAPE_PATH="$BASE/Boot_Features/RW_Scrapers/RW_Non_Footwear_Site_Scrape.md"
APPAREL_INVENTORY_DIR="$BASE/Inventory/Non-Footwear"
INCOMING_STOCK_SCRIPT="$BASE/Warehouse/Pull_Incoming_Stock.py"
PYTHON_BIN="$RUNTIME_BASE/.venv/bin/python"
LOG_DIR="$BASE/logs"
STAMP="$(date +%Y%m%d)"
LOG_FILE="$LOG_DIR/run_incoming_stock_${STAMP}_$(date +%H%M%S).log"
FAILED=0

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

run_step() {
  local label="$1"
  shift
  echo "[$(date --iso-8601=seconds)] Starting ${label}"
  if "$@"; then
    echo "[$(date --iso-8601=seconds)] Finished ${label}"
  else
    local status=$?
    FAILED=1
    echo "[$(date --iso-8601=seconds)] ${label} failed with exit code ${status}"
  fi
}

find_latest_merged_apparel_csv() {
  local latest_path=""
  local latest_mtime=0
  local path=""
  shopt -s nullglob
  for path in "$APPAREL_INVENTORY_DIR"/*_On_Hand_Non_Footwear.csv; do
    [[ -f "$path" ]] || continue
    local mtime=0
    mtime="$(stat -c %Y "$path" 2>/dev/null || echo 0)"
    if (( mtime > latest_mtime )); then
      latest_mtime="$mtime"
      latest_path="$path"
    fi
  done
  shopt -u nullglob
  printf '%s
' "$latest_path"
}

check_merged_apparel_sources() {
  local latest_csv=""
  latest_csv="$(find_latest_merged_apparel_csv)"
  if [[ -z "$latest_csv" ]]; then
    echo "Merged apparel inventory CSV not found in $APPAREL_INVENTORY_DIR"
    return 1
  fi
  if [[ ! -s "$latest_csv" ]]; then
    echo "Merged apparel inventory CSV is empty: $latest_csv"
    return 1
  fi
  if [[ ! -s "$APPAREL_SCRAPE_PATH" ]]; then
    echo "Merged apparel scrape markdown not found: $APPAREL_SCRAPE_PATH"
    return 1
  fi
  echo "Using merged apparel inventory CSV: $latest_csv"
  echo "Using merged apparel scrape markdown: $APPAREL_SCRAPE_PATH"
}

echo "[$(date --iso-8601=seconds)] Starting incoming stock refresh"
cd "$BASE"
export HOME="/home/justin"
export RW_HEADLESS="1"

run_step "merged apparel source check" check_merged_apparel_sources
run_step "incoming stock pull" "$PYTHON_BIN" "$INCOMING_STOCK_SCRIPT"

echo "[$(date --iso-8601=seconds)] Incoming stock refresh finished"
exit "$FAILED"
