#!/bin/bash

echo "Testing End-to-End Backtest Flow"
echo "================================"

# Wait for services to be ready
echo "Waiting for services to be ready..."
sleep 5

# Test 1: Check web-api health
echo -e "\n1. Checking web-api health..."
curl -s http://localhost:2003/health | jq .

# Test 2: Check orchestrator health
echo -e "\n2. Checking orchestrator health..."
curl -s http://localhost:2004/health | jq .

# Test 3: Create a backtest
echo -e "\n3. Creating a backtest..."
BACKTEST_RESPONSE=$(curl -s -X POST http://localhost:2003/api/backtests \
  -H "Content-Type: application/json" \
  -d '{
    "strategy": "SimpleMovingAverageCrossover",
    "symbols": ["AAPL"],
    "startDate": "2024-01-01",
    "endDate": "2024-01-31",
    "initialCapital": 100000,
    "config": {
      "commission": 0.001,
      "slippage": 0.0001
    }
  }')

echo "$BACKTEST_RESPONSE" | jq .

# Extract backtest ID
BACKTEST_ID=$(echo "$BACKTEST_RESPONSE" | jq -r .id)
echo "Backtest ID: $BACKTEST_ID"

# Test 4: Check backtest status
echo -e "\n4. Checking backtest status..."
sleep 2
curl -s http://localhost:2003/api/backtests/$BACKTEST_ID | jq .

# Test 5: Get backtest results (wait a bit for completion)
echo -e "\n5. Waiting for backtest to complete..."
for i in {1..10}; do
  sleep 2
  STATUS=$(curl -s http://localhost:2003/api/backtests/$BACKTEST_ID | jq -r .status)
  echo "Status: $STATUS"
  
  if [ "$STATUS" = "completed" ]; then
    echo -e "\n6. Getting backtest results..."
    curl -s http://localhost:2003/api/backtests/$BACKTEST_ID/results | jq .
    break
  fi
done

echo -e "\nEnd-to-End test complete!"