#!/bin/bash

# Simple Parallel Test using Maestro's built-in sharding
# This uses --shard-all to run the same test on multiple devices

set -e

echo "🚀 Starting Maestro parallel test with sharding..."

# Set your app ID here
export APP_ID="com.Humand.Demo.dev"  # iOS dev app ID
export USERNAME="henry"

open -a Simulator

# Create first simulator only if it doesn't exist
if ! xcrun simctl list devices | grep -q "Maestro_Test_1"; then
    echo "Creating simulator 1..."
    DEVICE_ID_1=$(xcrun simctl create "Maestro_Test_1" "iPhone 16" com.apple.CoreSimulator.SimRuntime.iOS-18-2)
else
    echo "Simulator 1 already exists"
    DEVICE_ID_1=$(xcrun simctl list devices | grep "Maestro_Test_1" | grep -oE '\([A-F0-9-]+\)' | tr -d '()')
fi
xcrun simctl boot "$DEVICE_ID_1" 2>/dev/null || echo "Simulator 1 already booted"

# Create second simulator only if it doesn't exist
if ! xcrun simctl list devices | grep -q "Maestro_Test_2"; then
    echo "Creating simulator 2..."
    DEVICE_ID_2=$(xcrun simctl create "Maestro_Test_2" "iPhone 16" com.apple.CoreSimulator.SimRuntime.iOS-18-2)
else
    echo "Simulator 2 already exists"
    DEVICE_ID_2=$(xcrun simctl list devices | grep "Maestro_Test_2" | grep -oE '\([A-F0-9-]+\)' | tr -d '()')
fi
xcrun simctl boot "$DEVICE_ID_2" 2>/dev/null || echo "Simulator 2 already booted"

echo "📱 Opening Simulator app..."

echo "⏳ Waiting for simulators to boot..."
sleep 2

# Kill any existing server processes
pkill -f "role-coordinator.py" 2>/dev/null || true
lsof -ti:3333 | xargs kill -9 2>/dev/null || true
sleep 1

# Start the role coordinator server
python3 e2e/role-coordinator.py &
SERVER_PID=$!
sleep 2

echo "▶️  Test 1: Search chat test"
maestro test e2e/flows/chats/search-chat.yml -e APP_ID=$APP_ID

echo "▶️  Test 2: Message parallel test"
maestro test --shard-all 2 e2e/flows/chats/parallel/send-message-parallel.yml -e APP_ID=$APP_ID
curl -X POST http://localhost:3333/reset -s > /dev/null

echo "▶️  Test 3: Image parallel test"
maestro test --shard-all 2 e2e/flows/chats/parallel/send-image-parallel.yml -e APP_ID=$APP_ID
curl -X POST http://localhost:3333/reset -s > /dev/null

echo "▶️  Test 4: Send multiple messages test"
maestro test --shard-all 2 e2e/flows/chats/parallel/send-multiple-messages-parallel.yml -e APP_ID=$APP_ID
curl -X POST http://localhost:3333/reset -s > /dev/null

echo "🛑 Stopping role coordinator server..."
kill $SERVER_PID 2>/dev/null || true

echo "🎉 All parallel tests completed!"
