#!/usr/bin/env bash
# Playwright codegen headed 录制 Priority1 公开询价路径
set -euo pipefail

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

export RPA_HEADLESS=false

DEFAULT_URL="https://www.priority1.com/instant-freight-quotes/"

FORBIDDEN=(
  "dashboard.priority1.com"
  "api.priority1.com"
)

check_url() {
  local url="$1"
  local pattern
  for pattern in "${FORBIDDEN[@]}"; do
    if echo "$url" | grep -qi "$pattern"; then
      echo "错误：禁止使用入口 URL：${pattern}" >&2
      echo "请使用公开询价页或首页" >&2
      exit 1
    fi
  done
}

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

启动 Playwright codegen（headed），录制 Priority1 公开询价完整路径。

默认起始页:
  ${DEFAULT_URL}

禁止入口:
  - dashboard.priority1.com
  - api.priority1.com

产出:
  .rpa/recordings/priority1-<时间戳>.js
  .rpa/priority1-storage.json
EOF
}

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

OUTPUT_DIR=".rpa/recordings"
STORAGE_PATH="${PRIORITY1_STORAGE_STATE_PATH:-.rpa/priority1-storage.json}"
mkdir -p "$OUTPUT_DIR" "$(dirname "$STORAGE_PATH")"

TIMESTAMP="$(date +%Y%m%d-%H%M%S)"
OUTPUT_FILE="${OUTPUT_DIR}/priority1-${TIMESTAMP}.js"
START_URL="${1:-$DEFAULT_URL}"

check_url "$START_URL"

echo "=== Priority1 RPA 录制（headed）==="
echo "RPA_HEADLESS=${RPA_HEADLESS}"
echo "禁止入口: dashboard.priority1.com / api.priority1.com"
echo "起始 URL: ${START_URL}"
echo "脚本产出: ${OUTPUT_FILE}"
echo "storageState: ${STORAGE_PATH}"
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")

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