#!/usr/bin/env sh
set -eu

# OpenAPI Breaking Change Detector (Minimal Script).
# 1. Compare the PR's openapi.provider.yaml with the version from the 'main' branch.
# 2. Detect basic breaking changes (deleted endpoints, changed methods, etc.)
# 3. Fail if breaking changes are found without explicit developer acknowledgement.

# Base branch to compare against
BASE_BRANCH="main"

die() {
  echo "ERROR: $*" >&2
  exit 1
}

# Create a temporary directory for main branch files
tmp_base=$(mktemp -d)
trap 'rm -rf "$tmp_base"' EXIT

check_breaking_changes() {
  module_path="$1"
  provider_file="spec/$module_path/openapi.provider.yaml"
  base_file="$tmp_base/$module_path/openapi.provider.yaml"

  [ -f "$provider_file" ] || return 0
  
  # Try to extract the file from the base branch
  mkdir -p "$(dirname "$base_file")"
  if ! git show "$BASE_BRANCH:$provider_file" > "$base_file" 2>/dev/null; then
    echo "New module or provider file detected: $provider_file. Skipping diff check."
    return 0
  fi

  echo "Checking breaking changes for $provider_file against $BASE_BRANCH..."

  # 1. Simple Endpoint/Method deletion check using grep/diff
  # Extract paths and methods (simple grep for '  /path:' and '    get|post|put|delete:')
  extract_endpoints() {
    grep -E "^[[:space:]]{2}/|^[[:space:]]{4}(get|post|put|delete|patch):" "$1" | sed 's/[[:space:]]*//g'
  }

  old_endpoints=$(mktemp)
  new_endpoints=$(mktemp)
  extract_endpoints "$base_file" > "$old_endpoints"
  extract_endpoints "$provider_file" > "$new_endpoints"

  deleted_count=$(comm -23 "$old_endpoints" "$new_endpoints" | wc -l)
  
  if [ "$deleted_count" -gt 0 ]; then
    echo "CRITICAL: Detected deleted endpoints or methods in $provider_file:"
    comm -23 "$old_endpoints" "$new_endpoints"
    rm -f "$old_endpoints" "$new_endpoints"
    return 1
  fi

  rm -f "$old_endpoints" "$new_endpoints"
  echo "OK: No obvious breaking changes in $provider_file endpoints."
  return 0
}

# Find modules
errors=0
for spec_dir in spec/*; do
  if [ -d "$spec_dir" ]; then
    module_name=$(basename "$spec_dir")
    if ! check_breaking_changes "$module_name"; then
      errors=$((errors + 1))
    fi
  fi
done

if [ "$errors" -gt 0 ]; then
  die "Breaking change check failed. Please revert changes or mark them as compatible."
fi

echo "All OpenAPI Breaking Change checks passed."
