#!/bin/bash
set -e

# Flow Replay Test - tests the self-healing replay system
# This script creates a sample flow YAML and runs it

export AGENT_BROWSER_EXECUTABLE_PATH=/Applications/Chromium.app/Contents/MacOS/Chromium
export AGENT_BROWSER_SESSION=douyin-flow-test

FLOW_FILE="/tmp/douyin-test-flow.yaml"

echo "========================================"
echo "  Douyin Flow Replay Test"
echo "========================================"

# Create a sample flow YAML
cat > "$FLOW_FILE" << 'EOF'
name: Douyin Homepage Test
description: Navigate to Douyin and verify page loads
steps:
  - action: navigate
    url: https://www.douyin.com
    waitForLoadState: domcontentloaded
    checkpoint:
      type: urlContains
      value: douyin.com

  - action: wait
    duration: 3000

  - action: snapshot

  - action: evaluate
    script: document.title
    checkpoint:
      type: textContains
      value: 抖音

  - action: screenshot
    path: ./douyin-homepage.png
EOF

echo "[1/4] Flow file created: $FLOW_FILE"
cat "$FLOW_FILE"
echo ""

# Check Chrome
echo "[2/4] Checking Chrome..."
if ! curl -s http://localhost:9221/json/version > /dev/null 2>&1; then
  echo "  Launching Chrome..."
  /Applications/Chromium.app/Contents/MacOS/Chromium --remote-debugging-port=9221 --user-data-dir=/tmp/chrome-debug2 &
  sleep 3
fi
echo "  Chrome ready"

# Clean and connect
echo ""
echo "[3/4] Connecting..."
node dist/cli.js kill --all 2>/dev/null || true
sleep 1
node dist/cli.js connect 9221
echo "  Connected"

# Run the flow
echo ""
echo "[4/4] Running flow..."
node dist/cli.js flow run "$FLOW_FILE" 2>&1 || echo "Flow completed with issues (check healing log)"

echo ""
echo "========================================"
echo "  Done! Check douyin-homepage.png if created."
echo "========================================"
