#!/usr/bin/env bash
# Playwright codegen headed 录制 Flock Freight get-a-quote
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

export RPA_HEADLESS=false

DEFAULT_URL="https://app.flockfreight.com/get-a-quote"

DEFAULT_LOGIN_URL="https://app.flockfreight.com/login"

usage() {
  cat <<EOF
用法:
  bash scripts/record-flock.sh [起始 URL]
  bash scripts/record-flock.sh --logged-in [起始 URL]

默认入口:
  匿名: ${DEFAULT_URL}
  登录后: ${DEFAULT_LOGIN_URL}

产出（匿名）:
  .rpa/recordings/flock-<时间戳>.js
  .rpa/flock-storage.json

产出（登录后）:
  .rpa/recordings/flock-logged-in-<时间戳>.js
  .rpa/flock-logged-in-storage.json

推荐: npm run record:flock -- --logged-in
EOF
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

MODE="anonymous"
START_URL=""
if [[ "${1:-}" == "--logged-in" || "${1:-}" == "--login" ]]; then
  MODE="logged-in"
  START_URL="${2:-}"
elif [[ -n "${1:-}" ]]; then
  START_URL="$1"
fi

OUTPUT_DIR=".rpa/recordings"
if [[ "$MODE" == "logged-in" ]]; then
  STORAGE_PATH="${FLOCK_LOGGED_IN_STORAGE_STATE_PATH:-.rpa/flock-logged-in-storage.json}"
  PREFIX="flock-logged-in"
  START_URL="${START_URL:-$DEFAULT_LOGIN_URL}"
else
  STORAGE_PATH="${FLOCK_STORAGE_STATE_PATH:-.rpa/flock-storage.json}"
  PREFIX="flock"
  START_URL="${START_URL:-$DEFAULT_URL}"
fi

mkdir -p "$OUTPUT_DIR" "$(dirname "$STORAGE_PATH")"

TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
OUTPUT_FILE="${OUTPUT_DIR}/${PREFIX}-${TIMESTAMP}.js"

echo "=== Flock Freight RPA 录制（headed / ${MODE}）==="
echo "RPA_HEADLESS=${RPA_HEADLESS}"
echo "起始 URL: ${START_URL}"
echo "脚本产出: ${OUTPUT_FILE}"
echo "storageState: ${STORAGE_PATH}"
if [[ "$MODE" == "logged-in" ]]; then
  echo "SOP: docs/rpa-flock-logged-in-sop.md"
fi
echo ""

ARGS=(
  codegen
  --target=javascript
  -o "$OUTPUT_FILE"
  --save-storage="$STORAGE_PATH"
)

if [[ -f "$STORAGE_PATH" ]]; then
  ARGS+=("--load-storage=$STORAGE_PATH")
  echo "已加载已有 storageState: ${STORAGE_PATH}"
fi

ARGS+=("$START_URL")

exec env RPA_HEADLESS=false npx playwright "${ARGS[@]}"
