#!/usr/bin/env bash
# task-121：Playwright codegen headed 录制 Mothership 匿名查价路径（GD-15）
set -euo pipefail

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

export RPA_HEADLESS=false

FORBIDDEN=(
  "dashboard.mothership.com"
  "www.mothership.com/quote"
)

check_url() {
  local url="$1"
  local pattern
  for pattern in "${FORBIDDEN[@]}"; do
    if echo "$url" | grep -qi "$pattern"; then
      echo "错误：禁止使用入口 URL（GD-15）：${pattern}" >&2
      echo "请使用 headed 录制验证的匿名公开报价 URL，见 docs/rpa-recording-sop.md" >&2
      exit 1
    fi
  done
}

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

启动 Playwright codegen（headed），录制 Mothership 匿名查价完整路径。

禁止入口（GD-15）:
  - dashboard.mothership.com
  - www.mothership.com/quote

产出:
  .rpa/recordings/mothership-<时间戳>.js
  .rpa/mothership-storage.json（若会话可持久化）

标准样例: LA 90001 → Dallas 75201，见 docs/rpa-recording-sop.md
EOF
}

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

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

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

if [[ -n "$START_URL" ]]; then
  check_url "$START_URL"
fi

echo "=== Mothership RPA 录制（headed）==="
echo "RPA_HEADLESS=${RPA_HEADLESS}"
echo "禁止入口: dashboard.mothership.com / www.mothership.com/quote"
echo "脚本产出: ${OUTPUT_FILE}"
echo "storageState: ${STORAGE_PATH}"
echo "SOP: docs/rpa-recording-sop.md"
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

if [[ -n "$START_URL" ]]; then
  ARGS+=("$START_URL")
else
  echo "未指定起始 URL：请在 codegen 浏览器中手动导航至匿名报价页"
fi

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