# Pre-push type check: catches errors locally in seconds vs. waiting for CI

# Get files changed compared to remote tracking branch
changed=$(git diff --name-only @{push} 2>/dev/null || git diff --name-only HEAD~3..HEAD 2>/dev/null || echo "")

# Build shared packages if gateway or observer changes are detected and dist/ is missing.
# CI builds these in setup-workspace; this ensures the same is true locally.
if echo "$changed" | grep -qE "^(gateway|observer|shared/policy-engine|shared/safe-house)/"; then
  if [ ! -d "shared/policy-engine/dist" ]; then
    echo "Building shared/policy-engine (dist/ missing)..."
    (cd shared/policy-engine && npm install --silent 2>/dev/null && npm run build) || exit 1
  fi
  if [ ! -d "shared/safe-house/dist" ]; then
    echo "Building shared/safe-house (dist/ missing)..."
    (cd shared/safe-house && npm install --silent 2>/dev/null && npm run build) || exit 1
  fi
fi

if echo "$changed" | grep -q "^gateway/"; then
  echo "Type-checking gateway..."
  (cd gateway && npx tsc --noEmit) || exit 1
fi

if echo "$changed" | grep -q "^observer/"; then
  echo "Type-checking observer..."
  (cd observer && npx tsc --noEmit) || exit 1
fi
