#!/usr/bin/env bash
# Show how a code change alters what Coolify sends to servers, for every golden case (tests/Golden).
#
# Usage:
#   ./scripts/golden-snapshot-diff save                 # 1. before you change code: save the current output
#   ./scripts/golden-snapshot-diff baseline             # 2. after the change: compare with the saved output
#   ./scripts/golden-snapshot-diff [git-ref]            # or compare with a git ref (default: main)
#   ./scripts/golden-snapshot-diff baseline -- --filter=postgresql   # extra Pest arguments
#
# Each run records every case with UPDATE_GOLDEN_SNAPSHOTS=1 and puts the committed expected files back.
# A git ref is exported with git archive to a temporary directory and recorded with the current harness
# and fixtures (tests/Golden, tests/Fixtures/golden), so the diff shows only the effect of the code change.
# The terminal shows one line per changed case; the full diff is written to storage/framework/testing/.
set -euo pipefail

repo="$(git -C "$(dirname "$0")/.." rev-parse --show-toplevel)"
mode="${1:-main}"
shift || true
[[ "${1:-}" == "--" ]] && shift
pest_args=("$@")

testing="$repo/storage/framework/testing"   # gitignored, same file system as the repository
saved="$testing/golden-snapshots-baseline"
report="$testing/golden-snapshot-diff.diff"
mkdir -p "$testing"
work="$(mktemp -d "$testing/golden-snapshot-diff.XXXXXX")"
trap 'rm -rf "$work"' EXIT

# Record every case in <dir> and copy its expected files (one folder per area) to <target>.
record_into() {
  local dir="$1" target="$2" label="$3" golden="$1/tests/Fixtures/golden" backup="$work/golden-backup" status=0
  echo "==> Recording on $label"
  # The run rewrites the expected files: put the committed ones back afterwards, so the repository is unchanged.
  rm -rf "$backup"
  cp -r "$golden" "$backup"
  (cd "$dir" && UPDATE_GOLDEN_SNAPSHOTS=1 php artisan test --compact tests/Golden "${pest_args[@]}" >"$work/run.log" 2>&1) || status=$?
  rm -rf "$target"
  mkdir -p "$target"
  for expected in "$golden"/*/expected; do
    [[ -d "$expected" ]] && cp -r "$expected" "$target/$(basename "$(dirname "$expected")")"
  done
  rm -rf "$golden"
  mv "$backup" "$golden"
  if [[ $status -ne 0 ]]; then
    echo "Test run on $label failed:" >&2
    tail -30 "$work/run.log" >&2
    exit 1
  fi
}

case "$mode" in
  save)
    record_into "$repo" "$saved" "working tree"
    echo "Saved baseline: $saved"
    echo "Change the code, then run: ./scripts/golden-snapshot-diff baseline"
    exit 0
    ;;
  baseline)
    [[ -d "$saved" ]] || { echo "No saved baseline. Run ./scripts/golden-snapshot-diff save first." >&2; exit 1; }
    base_label="saved baseline"
    cp -r "$saved" "$work/base-expected"
    ;;
  *)
    base_label="$mode"
    base="$work/base"
    mkdir -p "$base"
    echo "==> Exporting $mode ($(git -C "$repo" rev-parse --short "$mode"))"
    git -C "$repo" archive "$mode" | tar -x -C "$base"
    # Hard links: fast and no extra disk space. A symlink would make Composer load the classes of $repo.
    cp -al "$repo/vendor" "$base/vendor"
    [[ -f "$repo/.env" ]] && cp "$repo/.env" "$base/.env"
    rm -rf "$base/tests/Golden" "$base/tests/Fixtures/golden"
    cp -r "$repo/tests/Golden" "$base/tests/Golden"
    cp -r "$repo/tests/Fixtures/golden" "$base/tests/Fixtures/golden"
    record_into "$base" "$work/base-expected" "$mode"
    ;;
esac

record_into "$repo" "$work/current-expected" "working tree"

echo
if diff -ru "$work/base-expected" "$work/current-expected" | sed -E "s#$work/(base|current)-expected/##g" >"$report"; then
  echo "No differences from $base_label: every golden case sends the same commands and files."
  exit 0
fi

# The last line of a case is its error: a new error means the operation failed on that side.
case_error() { grep '^error: ' "$1" | grep -v '^error: null$' | cut -c8-130 || true; }

summary() {
  local file="$1" base_file="$work/base-expected/$1" current_file="$work/current-expected/$1" base_error current_error
  [[ -f "$base_file" ]] || { echo "  new case        $file"; return; }
  [[ -f "$current_file" ]] || { echo "  removed case    $file"; return; }
  base_error="$(case_error "$base_file")"
  current_error="$(case_error "$current_file")"
  if [[ -n "$current_error" && "$current_error" != "$base_error" ]]; then
    echo "  CURRENT ERROR   $file: $current_error"
  else
    echo "  changed         $file (+$(diff "$base_file" "$current_file" | grep -c '^>' || true) -$(diff "$base_file" "$current_file" | grep -c '^<' || true))"
  fi
}

changed_cases=()
while IFS= read -r file; do
  cmp -s "$work/base-expected/$file" "$work/current-expected/$file" || changed_cases+=("$file")
done < <( (cd "$work/base-expected" && find . -name '*.yaml'; cd "$work/current-expected" && find . -name '*.yaml') | sed 's|^\./||' | sort -u)

echo "${#changed_cases[@]} case(s) differ from $base_label:"
for file in "${changed_cases[@]}"; do summary "$file"; done
echo
echo "Full diff: $report"
exit 1
