#!/bin/bash
set -uo pipefail

BASE="/media/justin/syncPi/Shared/61_RW_Site/Pulled_Info"
RUNTIME_BASE="/home/justin/rw_inventory"
OPEN_SCRIPT="$BASE/Powerbi_Background/Open_PowerBi.py"
FOOTWEAR_SCRIPT="$BASE/Inventory/Pull_On_Hand_Footwear.py"
APPAREL_SCRIPT="$BASE/Inventory/Pull_Merged_Apparel.py"
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"
SESSION_FILE="$BASE/Powerbi_Background/config/powerbi_session.json"
DOWNLOAD_DIR="$BASE/Powerbi_Background/downloads"
LOG_DIR="$BASE/logs"
STAMP="$(date +%Y%m%d)"
LOG_FILE="$LOG_DIR/run_${STAMP}_$(date +%H%M%S).log"
OPEN_PID=""
FAILED=0
POWERBI_READY=0

mkdir -p "$DOWNLOAD_DIR" "$LOG_DIR" "$BASE/Inventory/Footwear" "$BASE/Inventory/Non-Footwear" "$(dirname "$SESSION_FILE")"
rm -f "$SESSION_FILE"

cleanup() {
  if [[ -n "$OPEN_PID" ]] && kill -0 "$OPEN_PID" 2>/dev/null; then
    kill "$OPEN_PID" 2>/dev/null || true
    wait "$OPEN_PID" 2>/dev/null || true
  fi
  OPEN_PID=""
}
trap cleanup EXIT

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\n' "$latest_path"
}

check_merged_apparel_sources() {
  local expected_csv="$APPAREL_INVENTORY_DIR/${STAMP}_On_Hand_Non_Footwear.csv"
  local latest_csv=""
  latest_csv="$(find_latest_merged_apparel_csv)"
  if [[ ! -f "$expected_csv" ]]; then
    echo "Merged apparel inventory CSV for today was not created: $expected_csv"
    return 1
  fi
  if [[ ! -s "$expected_csv" ]]; then
    echo "Merged apparel inventory CSV is empty: $expected_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: $expected_csv"
  if [[ -n "$latest_csv" && "$latest_csv" != "$expected_csv" ]]; then
    echo "Latest detected merged apparel CSV before verification: $latest_csv"
  fi
  echo "Using merged apparel scrape markdown: $APPAREL_SCRAPE_PATH"
}

echo "[$(date --iso-8601=seconds)] Starting current inventory pull"
cd "$BASE"
export HOME="/home/justin"
export POWERBI_SESSION_FILE="$SESSION_FILE"
export POWERBI_DOWNLOAD_DIR="$DOWNLOAD_DIR"
export POWERBI_OUTPUT_STAMP="$STAMP"
export POWERBI_READY_TIMEOUT="300"
export POWERBI_MFA_ACTION_COOLDOWN_SECONDS="30"
export POWERBI_MFA_POST_TRIGGER_WAIT_SECONDS="35"
export GECKODRIVER_PATH="$RUNTIME_BASE/bin/geckodriver"

"$PYTHON_BIN" "$OPEN_SCRIPT" --headless &
OPEN_PID=$!
echo "Open_PowerBi PID: $OPEN_PID"

for _ in $(seq 1 300); do
  if [[ -s "$SESSION_FILE" ]]; then
    echo "Session file ready: $SESSION_FILE"
    POWERBI_READY=1
    break
  fi
  if ! kill -0 "$OPEN_PID" 2>/dev/null; then
    echo "Open_PowerBi exited before session file was created"
    FAILED=1
    break
  fi
  sleep 1
done

if [[ ! -s "$SESSION_FILE" ]]; then
  echo "Power BI session not ready; skipping footwear and merged apparel pulls."
  FAILED=1
fi

if [[ "$POWERBI_READY" -eq 1 ]]; then
  run_step "footwear pull" "$PYTHON_BIN" "$FOOTWEAR_SCRIPT"
  run_step "merged apparel pull" "$PYTHON_BIN" "$APPAREL_SCRIPT"
  cleanup
fi
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)] Inventory pull finished"
exit "$FAILED"
