#!/usr/bin/env bash
# Emit per-service + aggregate change flags for the CI / build workflows.
#
# Reads:
#   BASE_SHA — diff base. Empty / unreachable → emit everything as true.
#   HEAD_SHA — diff target. Defaults to HEAD.
#
# Writes key=value lines to $GITHUB_OUTPUT (defaults to /dev/stdout for local runs).
#
# Keys emitted:
#   admin, backend, sdk, portal, tts, crawler, dsms_gateway, dsms_node
#   any_python, any_node, any

set -euo pipefail

BASE_SHA="${BASE_SHA:-}"
HEAD_SHA="${HEAD_SHA:-HEAD}"
OUT="${GITHUB_OUTPUT:-/dev/stdout}"

ALL_KEYS=(admin backend sdk portal tts crawler dsms_gateway dsms_node any_python any_node any)

emit() {
  echo "$1=$2" >> "$OUT"
}

emit_all_true() {
  reason=$1
  echo "→ rebuild all: $reason"
  for k in "${ALL_KEYS[@]}"; do
    emit "$k" true
  done
}

if [ -z "$BASE_SHA" ]; then
  emit_all_true "no BASE_SHA provided"
  exit 0
fi

if ! git rev-parse --verify "${BASE_SHA}^{commit}" >/dev/null 2>&1; then
  emit_all_true "BASE_SHA ${BASE_SHA} unreachable"
  exit 0
fi

changed=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA" || true)
echo "Changed files since ${BASE_SHA}:"
echo "${changed:-(none)}"
echo "---"

check() {
  key=$1
  path=$2
  if echo "$changed" | grep -q "^${path}/"; then
    emit "$key" true
    echo "  ${key} (${path}/): true"
  else
    emit "$key" false
    echo "  ${key} (${path}/): false"
  fi
}

check admin         admin-compliance
check backend       backend-compliance
check sdk           ai-compliance-sdk
check portal        developer-portal
check tts           compliance-tts-service
check crawler       document-crawler
check dsms_gateway  dsms-gateway
check dsms_node     dsms-node

# Aggregate flags
if echo "$changed" | grep -qE "^(backend-compliance|document-crawler|dsms-gateway|compliance-tts-service)/"; then
  emit any_python true
  echo "  any_python: true"
else
  emit any_python false
  echo "  any_python: false"
fi

if echo "$changed" | grep -qE "^(admin-compliance|developer-portal)/"; then
  emit any_node true
  echo "  any_node: true"
else
  emit any_node false
  echo "  any_node: false"
fi

if [ -n "$changed" ]; then
  emit any true
  echo "  any: true"
else
  emit any false
  echo "  any: false"
fi
