#!/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"
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_footwear_${STAMP}_$(date +%H%M%S).log"
OPEN_PID=""
FAILED=0
POWERBI_READY=0

mkdir -p "$DOWNLOAD_DIR" "$LOG_DIR" "$BASE/Inventory/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

echo "[$(date --iso-8601=seconds)] Starting footwear 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 [[ "$POWERBI_READY" -eq 1 ]]; then
  echo "[$(date --iso-8601=seconds)] Starting footwear pull"
  if "$PYTHON_BIN" "$FOOTWEAR_SCRIPT"; then
    echo "[$(date --iso-8601=seconds)] Finished footwear pull"
  else
    status=$?
    FAILED=1
    echo "[$(date --iso-8601=seconds)] Footwear pull failed with exit code $status"
  fi
  cleanup
else
  echo "Power BI session not ready; skipping footwear pull."
  FAILED=1
fi

echo "[$(date --iso-8601=seconds)] Footwear inventory pull finished"
exit "$FAILED"
