#!/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: //')

WORKSPACE=$(pwd)
UNITY_INSTALL_PATH="/Applications/Unity/Hub/Editor"
BUILD_DIR=$1
LOG_PATH=$2
BUILD_ADDRESSABLES=${3:-true}
ADDRESSABLES_BUILD_LAYOUT=${4:-$BUILD_ADDRESSABLES}

echo "Building Mac in $BUILD_DIR"
echo "Build Addressables: $BUILD_ADDRESSABLES"
echo "Generate Addressables build layout: $ADDRESSABLES_BUILD_LAYOUT"

echo "Cleaning up $BUILD_DIR"
/bin/rm -rf "$BUILD_DIR"
/bin/mkdir -p "$BUILD_DIR"

if [ -n "${DOTNET_ROOT:-}" ]; then
    export PATH="$DOTNET_ROOT:$PATH"
    export DOTNET_HOST_PATH="$DOTNET_ROOT/dotnet"
fi
dotnet --list-sdks

# Use custom build script that builds Addressables before the player
# Capture exit code to show log on failure
set +e
${UNITY_INSTALL_PATH}/${UNITY_VERSION}/Unity.app/Contents/MacOS/Unity \
   -nographics \
   -batchmode \
   -quit \
   -executeMethod BuildScript.BuildMacPlayer \
   -buildPath "$BUILD_DIR/eagle0.app" \
   -buildAddressables "$BUILD_ADDRESSABLES" \
   -addressablesBuildLayout "$ADDRESSABLES_BUILD_LAYOUT" \
   -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 build failed with exit code $UNITY_EXIT_CODE"
    echo "=== Unity Editor Log (last 200 lines) ==="
    tail -200 "$LOG_PATH" || echo "Could not read log file at $LOG_PATH"
    echo "=== End of Unity Editor 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

# Fail the build if any prefab references are broken — this produces a player
# that launches but has null Inspector fields, which is hard to debug.
if grep -q "Missing Prefab" "$LOG_PATH"; then
    echo ""
    echo "ERROR: Build has missing prefab references (likely stale Library cache):"
    grep "Missing Prefab" "$LOG_PATH"
    exit 1
fi

if grep -q "Build asset version error" "$LOG_PATH"; then
    echo ""
    echo "ERROR: Build has asset version mismatches (likely stale Library cache):"
    grep "Build asset version error" "$LOG_PATH" | head -5
    exit 1
fi
