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

root="$(git rev-parse --show-toplevel)"
ags="$root/x/agent-git-service"

fail() {
  echo "AGS repository mutation boundary: $1" >&2
  exit 1
}

if ! command -v go >/dev/null 2>&1; then
  echo "go is not available; skipping the AGS repository mutation inventory and import-boundary checks (run where a Go toolchain exists)" >&2
else
  go run -tags ags_inventory "$root/guardrails/ags/check-repository-mutation-inventory.go" "$root" ||
    fail "Store methods, service callsites, and child commands must remain explicitly classified"
  "$root/guardrails/ags/check-repositorymutation-import-boundary.sh" ||
    fail "private repository mutation owner must remain under the service-only Go internal boundary"
fi

if rg -n '(Flock|LOCK_SH|LOCK_EX|\.ags-repository-mutation-fences|acquireRepositoryMutationFence|acquireRepositoryWriterMutex)' \
  "$ags/internal" "$ags/server" --glob '*.go' --glob '!**/*_test.go'; then
  fail "repository-level filesystem locks must not be reintroduced"
fi

if rg -n '(SealRepositoryForMigration|RenewRepositoryMigrationProof|ValidateRepositoryMigrationProof|AbortRepositoryMigrationSealBeforeImport|AbortFailedRepositorySeal)\(' \
  "$ags/internal/rest" "$ags/internal/graphql" "$ags/internal/githttp" "$ags/server" --glob '!**/*_test.go'; then
  fail "disabled migration seal/proof capabilities must remain unreachable from public routes"
fi

for method in SealRepositoryForMigration RenewRepositoryMigrationProof ValidateRepositoryMigrationProof AbortRepositoryMigrationSealBeforeImport AbortFailedRepositorySeal; do
  rg -q "func \(\*Service\) $method" "$ags/internal/service/repository_migration_freeze.go" ||
    fail "$method compatibility method is missing"
done
count="$(rg -c 'return (nil, )?ErrRepositoryMigrationUnavailable' "$ags/internal/service/repository_migration_freeze.go")"
[[ "$count" -eq 5 ]] || fail "every migration seal/proof compatibility method must fail explicitly"

if rg -n 'AcquireRepositoryMutationCapability|RepositoryMutationCapability|repositorymutation' \
  "$ags/internal/githttp" "$ags/server" --glob '*.go' --glob '!**/*_test.go'; then
  fail "githttp/server must use operation-specific Service APIs, never mutation sessions or private owners"
fi
rg -q 'ServeRepositoryReceivePack' "$ags/internal/githttp/handler.go" ||
  fail "receive-pack must delegate its full lifecycle to the Service owner"
rg -q 'PushRepositoryMirror' "$ags/server/repository_mirror.go" ||
  fail "typed mirror must delegate its full lifecycle to the Service owner"

echo "AGS repository mutation boundary passed."
