#!/usr/bin/env bash

set -euxo pipefail

# Read Unity version from project file
UNITY_VERSION=$(grep "m_EditorVersion:" src/main/csharp/net/eagle0/clients/unity/eagle0/ProjectSettings/ProjectVersion.txt | head -1 | sed 's/m_EditorVersion: //')

# Use runner-specific build directory if EAGLE0_BUILD_DIR is set, otherwise default
BUILD_BASE="${EAGLE0_BUILD_DIR:-/tmp/eagle0}"

WORKSPACE=$(pwd)
UNITY_INSTALL_PATH="/Applications/Unity/Hub/Editor"
LOG_PATH="${BUILD_BASE}/editor_editmode_tests.log"
RESULTS_PATH="${BUILD_BASE}/editmode-test-results.xml"

mkdir -p "$BUILD_BASE"

echo "Building protos"
./scripts/build_protos.sh

echo "Running Unity EditMode tests"

set +e
"${UNITY_INSTALL_PATH}/${UNITY_VERSION}/Unity.app/Contents/MacOS/Unity" \
   -nographics \
   -batchmode \
   -quit \
   -executeMethod eagle0.Tests.DynamicTextBindingTestRunner.Run \
   -testResults "$RESULTS_PATH" \
   -logFile "$LOG_PATH" \
   -projectPath "$WORKSPACE/src/main/csharp/net/eagle0/clients/unity/eagle0"
UNITY_EXIT_CODE=$?
set -e

if [ $UNITY_EXIT_CODE -ne 0 ]; then
    echo ""
    echo "Unity EditMode tests failed with exit code $UNITY_EXIT_CODE"
    echo "=== Unity EditMode Test Log (last 200 lines) ==="
    tail -200 "$LOG_PATH" || echo "Could not read log file at $LOG_PATH"
    echo "=== End of Unity EditMode Test Log ==="
    exit $UNITY_EXIT_CODE
fi

if [ ! -f "$LOG_PATH" ]; then
    echo ""
    echo "ERROR: Unity exited successfully but did not write an editor log at $LOG_PATH"
    exit 1
fi

if [ ! -f "$RESULTS_PATH" ]; then
    echo ""
    echo "ERROR: Unity exited successfully but did not write test results at $RESULTS_PATH"
    exit 1
fi

echo "Unity EditMode tests complete"
