#!/usr/bin/env bash
# Master script to run all automated tasks in parallel

set -e

cd "$(dirname "$0")/../.."
FORGE_SCOPE="${FORGE_SCOPE:-full}"

echo "=== 🚀 Running All Automated Tasks ==="
echo ""

# Create logs directory
mkdir -p logs

# Array to store background job PIDs
declare -a pids=()

# Function to run task and track PID
run_parallel_task() {
    local task_name="$1"
    local task_command="$2"
    local log_file="logs/${task_name}.log"
    
    echo "Starting: $task_name"
    (
        eval "$task_command" > "$log_file" 2>&1
        if [ $? -eq 0 ]; then
            echo "✅ $task_name: SUCCESS"
        else
            echo "❌ $task_name: FAILED (check $log_file)"
        fi
    ) &
    
    pids+=($!)
    echo "  PID: $!"
}

# Task 1: Validate all scripts
run_parallel_task "validate-scripts" "./scripts/automation/validate-all-scripts.sh"

# Task 2: Scope review
run_parallel_task "scope-review" "./scripts/automation/scope-review.sh"

# Task 3: Compile Foundry contracts
run_parallel_task "compile-foundry" "bash scripts/forge/scope.sh build \"$FORGE_SCOPE\" --force 2>&1 | grep -v 'ccip-integration' || true"

# Task 4: Run Foundry tests
run_parallel_task "test-foundry" "bash scripts/forge/scope.sh test \"$FORGE_SCOPE\" --no-match-path 'test/ccip-integration/*' 2>&1 || true"

# Task 5: Check environment configuration
run_parallel_task "check-env" "./scripts/deployment/verify-env.sh 2>&1 || echo 'Env check skipped'"

# Task 6: Validate deployment scripts syntax
run_parallel_task "validate-deployment-scripts" "find scripts/deployment -name '*.sh' -exec bash -n {} \; 2>&1 || true"

# Task 7: Check contract compilation status
run_parallel_task "check-contracts" "find contracts -name '*.sol' -type f | wc -l"

# Task 8: Count documentation files
run_parallel_task "count-docs" "find docs -name '*.md' -type f | wc -l"

# Wait for all tasks
echo ""
echo "Waiting for all tasks to complete..."
for pid in "${pids[@]}"; do
    wait $pid
done

echo ""
echo "=== ✅ All Automated Tasks Complete ==="
echo "Check logs/ directory for detailed output"
