#!/usr/bin/env bash
set -euo pipefail

root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
go_out="$root/packages/contracts/gen/go"
dart_out="$root/apps/client/lib/src/generated"

snapshot_dir="$(mktemp -d)"
trap 'rm -rf "$snapshot_dir"' EXIT

snapshot_go="$snapshot_dir/go"
snapshot_dart="$snapshot_dir/dart"
mkdir -p "$snapshot_go" "$snapshot_dart"

if [ -d "$go_out" ]; then
  cp -R "$go_out/." "$snapshot_go/"
fi
if [ -d "$dart_out" ]; then
  cp -R "$dart_out/." "$snapshot_dart/"
fi

"$root/bin/contracts-gen"

drift=0

if ! diff -ru "$snapshot_go" "$go_out" >/dev/null; then
  echo "contracts-check: Go generated output drift detected under $go_out" >&2
  diff -ru "$snapshot_go" "$go_out" >&2 || true
  drift=1
fi

if ! diff -ru "$snapshot_dart" "$dart_out" >/dev/null; then
  echo "contracts-check: Dart generated output drift detected under $dart_out" >&2
  diff -ru "$snapshot_dart" "$dart_out" >&2 || true
  drift=1
fi

if [ "$drift" -ne 0 ]; then
  echo "contracts-check: run bin/contracts-gen and commit the regenerated output" >&2
  exit 1
fi
