#!/bin/bash
set -e

echo "🔥 PLAYWRIGHT RUN SCRIPT"
echo "⚙️ Raw args: $@"

# Parse --automationIds and --customTags input from args
AUTOMATION_IDS=""
CUSTOM_TAGS=""
for arg in "$@"; do
  case $arg in
    --automationIds=*)
      AUTOMATION_IDS="${arg#*=}"
      shift
      ;;
    --customTags=*)
      CUSTOM_TAGS="${arg#*=}"
      shift
      ;;
  esac
done

echo "🔍 automationIds: ${AUTOMATION_IDS}"
echo "🔍 customTags: ${CUSTOM_TAGS}"

TIMESTAMP=$(date +%m%d%Y_%H%M%S)
PRODUCT_NAME=${PRODUCT_NAME:-unknown_product}
PLAN_ID=${PLAN_ID:-unknown_plan}
RUN_ID=${RUN_ID:-unknown_run}
BUCKET_NAME=${BUCKET_NAME:-your-default-bucket}
TEST_ENVIRONMENT=${TEST_ENVIRONMENT:-QA}

# Ensure results dir
RESULTS_DIR="test-results"
PW_HTML_DIR="playwright-report"
mkdir -p "$RESULTS_DIR"

# Build grep regex for Playwright
GREP_ARG=""
GREP_PATTERNS=""

if [ -n "$AUTOMATION_IDS" ]; then
  RAW_IDS=$(echo "$AUTOMATION_IDS" | sed "s/^['\"]//;s/['\"]$//")
  CLEANED_IDS="${RAW_IDS//,/|}"
  GREP_PATTERNS="${CLEANED_IDS}"
  echo "🔎 Automation IDs pattern: ${CLEANED_IDS}"
fi

if [ -n "$CUSTOM_TAGS" ]; then
  RAW_TAGS=$(echo "$CUSTOM_TAGS" | sed "s/^['\"]//;s/['\"]$//")
  CLEANED_TAGS="${RAW_TAGS//,/|}"
  
  if [ -n "$GREP_PATTERNS" ]; then
    GREP_PATTERNS="${GREP_PATTERNS}|${CLEANED_TAGS}"
  else
    GREP_PATTERNS="${CLEANED_TAGS}"
  fi
  echo "🔎 Custom tags pattern: ${CLEANED_TAGS}"
fi

if [ -n "$GREP_PATTERNS" ]; then
  GREP_ARG="--grep=@(${GREP_PATTERNS})"
  echo "🔎 Final grep pattern: $GREP_ARG"
fi

# Run Playwright
echo "🚀 Running Playwright..."
set +e
TEST_ENVIRONMENT="${TEST_ENVIRONMENT}" npx playwright test \
  --reporter=list,json,html \
  --output "$RESULTS_DIR" \
  $GREP_ARG \
  | tee results_logs.txt
EXIT_CODE=${PIPESTATUS[0]}
set -e

# Locate JSON report (aggregate.json if configured; fallback to last json)
JSON_REPORT=$(ls $RESULTS_DIR/*.json 2>/dev/null | tail -n 1)
if [ -z "$JSON_REPORT" ]; then
  echo "⚠️ No Playwright JSON report found in $RESULTS_DIR"
else
  echo "📄 Using JSON report: $JSON_REPORT"
fi

# Zip HTML report folder
ZIP_NAME="${PRODUCT_NAME}_${TIMESTAMP}.zip"
ZIP_PATH="/tmp/${ZIP_NAME}"
if [ -d "$PW_HTML_DIR" ]; then
  echo "📦 Zipping Playwright HTML report..."
  zip -r "$ZIP_PATH" "$PW_HTML_DIR"
fi

# Copy artifacts to shared volume for EC2 to upload
mkdir -p /shared/test-logs
if [ -f "$ZIP_PATH" ]; then
  echo "📁 Copying ZIP to shared volume: ${ZIP_NAME}"
  cp "$ZIP_PATH" "/shared/test-logs/${ZIP_NAME}" || echo "❌ Failed to copy ZIP to shared volume"
fi
if [ -f "$PW_HTML_DIR/index.html" ]; then
  echo "📁 Copying HTML to shared volume: index.html"
  cp "$PW_HTML_DIR/index.html" "/shared/test-logs/index.html" || echo "❌ Failed to copy HTML to shared volume"
fi

# Post results to HAVEN API
PLAN_ID="${PLAN_ID}" RUN_ID="${RUN_ID}" TEST_ENVIRONMENT="${TEST_ENVIRONMENT}" node /app/syncPlaywrightResults.js "$JSON_REPORT" || echo "⚠️ Result sync script finished with warnings"

exit $EXIT_CODE 