#!/usr/bin/env bash

# Build iOS Addressables only (no player build)
# This switches Unity to iOS target and builds addressables for CDN upload

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)

echo "Building protos"
./scripts/build_protos.sh
UNITY_INSTALL_PATH="/Applications/Unity/Hub/Editor"
LOG_PATH=${1:-"${BUILD_BASE}/editor_ios_addressables.log"}

echo "Building iOS Addressables"

mkdir -p "$(dirname "$LOG_PATH")"

# Build Addressables for iOS target
# Uses BuildiOSAddressables which explicitly switches build target
# 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.BuildiOSAddressables \
   -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

echo "iOS Addressables build complete"
echo "Bundles should be in: $WORKSPACE/src/main/csharp/net/eagle0/clients/unity/eagle0/ServerData/iOS/"
