#!/usr/bin/env bash

set -euo pipefail

BASE_SHA=${1:-}
HEAD_SHA=${2:-HEAD}
OUTPUT_FILE=${GITHUB_OUTPUT:-}

if [ -z "$BASE_SHA" ] || [[ "$BASE_SHA" =~ ^0+$ ]]; then
    echo "No usable base SHA for this run; building Addressables as a safe default."
    changed=true
elif ! git cat-file -e "$BASE_SHA^{commit}"; then
    echo "Base SHA $BASE_SHA is not available locally; building Addressables as a safe default."
    changed=true
else
    UNITY_PROJECT="src/main/csharp/net/eagle0/clients/unity/eagle0"
    ADDRESSABLE_PREFIXES=(
        "$UNITY_PROJECT/Assets/AddressableAssetsData/"
        "$UNITY_PROJECT/Assets/Eagle/Effects/"
        "$UNITY_PROJECT/Assets/Hex Tiles/"
        "$UNITY_PROJECT/Assets/TileableBridgePack/"
        "$UNITY_PROJECT/Assets/Shardok/LargeFlames.prefab"
        "$UNITY_PROJECT/Assets/Shardok/soundEffects/"
        "$UNITY_PROJECT/Assets/Shardok/Sounds/"
        "$UNITY_PROJECT/Assets/Medieval Combat Sounds/"
        "$UNITY_PROJECT/Assets/Magic Spells Sound Effects LITE/"
        "$UNITY_PROJECT/Assets/Fantasy Interface Sounds/"
        "$UNITY_PROJECT/Assets/AustraliaAnimalsPackv1/"
        "$UNITY_PROJECT/Assets/Music/"
        "$UNITY_PROJECT/Assets/Editor/BuildScript.cs"
    )

    is_addressables_input() {
        local file="$1"
        for prefix in "${ADDRESSABLE_PREFIXES[@]}"; do
            if [[ "$file" == "$prefix"* ]]; then
                return 0
            fi
        done

        return 1
    }

    changed=false
    while IFS= read -r file; do
        if is_addressables_input "$file"; then
            echo "Addressables-impacting change: $file"
            changed=true
            break
        fi
    done < <(git diff --name-only "$BASE_SHA" "$HEAD_SHA")
fi

if [ "$changed" = "true" ]; then
    echo "Building Addressables because their inputs changed."
else
    echo "Skipping Addressables build; no Addressables inputs changed."
fi

if [ -n "$OUTPUT_FILE" ]; then
    echo "changed=$changed" >> "$OUTPUT_FILE"
else
    echo "changed=$changed"
fi
