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

repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
cd "${repo_root}/desktop"

goimports_bin="${GOIMPORTS:-}"
if [[ -z "${goimports_bin}" ]]; then
  if command -v goimports >/dev/null 2>&1; then
    goimports_bin="$(command -v goimports)"
  elif command -v go >/dev/null 2>&1; then
    tmp_bin_dir="$(mktemp -d)"
    trap 'rm -rf "${tmp_bin_dir}"' EXIT
    GOBIN="${tmp_bin_dir}" go install golang.org/x/tools/cmd/goimports@v0.44.0
    goimports_bin="${tmp_bin_dir}/goimports"
  else
    echo "goimports is required and go is not available to install it" >&2
    exit 127
  fi
fi

files=()
while IFS= read -r file; do
  files+=("${file}")
done < <(find internal/agent -name '*.go' -not -path '*/testdata/*' | LC_ALL=C sort)

if [[ "${#files[@]}" -eq 0 ]]; then
  exit 0
fi

unformatted="$(${goimports_bin} -l -local github.com/tidbcloud/AgentTeam "${files[@]}")"
if [[ -n "${unformatted}" ]]; then
  cat >&2 <<'MSG'
desktop/internal/agent Go files are not goimports-formatted.
Run:
  cd desktop
  goimports -w -local github.com/tidbcloud/AgentTeam $(find internal/agent -name '*.go' -not -path '*/testdata/*' | sort)
MSG
  printf '%s\n' "${unformatted}" >&2
  exit 1
fi
