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

cd "$(dirname "$0")/.."

usage() {
  cat <<'EOF'
Usage:
  ./scripts/safe_sync.sh "Commit message"

Environment options:
  SAFE_SYNC_TEST_CMD   Optional command run after py_compile (example: "pytest -q")
  SAFE_SYNC_SKIP_PUSH  Set to 1 to skip git push

Behavior:
  1) Validates all tracked Python files with py_compile
  2) Runs optional test command if SAFE_SYNC_TEST_CMD is set
  3) git add -A, commit, and push (unless SAFE_SYNC_SKIP_PUSH=1)
EOF
}

if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then
  usage
  exit 0
fi

if [ -z "${1:-}" ]; then
  echo "Missing commit message."
  usage
  exit 1
fi

COMMIT_MSG="$1"

if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
  echo "Not inside a git repository."
  exit 1
fi

BRANCH="$(git rev-parse --abbrev-ref HEAD)"
if [ -z "${BRANCH}" ] || [ "${BRANCH}" = "HEAD" ]; then
  echo "Detached HEAD is not supported for safe_sync."
  exit 1
fi

# macOS ships Bash 3.2 by default, which does not support mapfile.
PY_FILES=()
while IFS= read -r py_file; do
  PY_FILES+=("$py_file")
done < <(git ls-files '*.py')
if [ "${#PY_FILES[@]}" -gt 0 ]; then
  echo "[safe_sync] Running py_compile on ${#PY_FILES[@]} Python files ..."
  python3 -m py_compile "${PY_FILES[@]}"
else
  echo "[safe_sync] No tracked Python files found."
fi

if [ -n "${SAFE_SYNC_TEST_CMD:-}" ]; then
  echo "[safe_sync] Running test command: ${SAFE_SYNC_TEST_CMD}"
  eval "${SAFE_SYNC_TEST_CMD}"
fi

echo "[safe_sync] Staging changes ..."
git add -A

if git diff --cached --quiet; then
  echo "[safe_sync] No staged changes to commit."
  exit 0
fi

echo "[safe_sync] Creating commit ..."
git commit -m "${COMMIT_MSG}"

if [ "${SAFE_SYNC_SKIP_PUSH:-0}" = "1" ]; then
  echo "[safe_sync] Commit created. Push skipped (SAFE_SYNC_SKIP_PUSH=1)."
  exit 0
fi

if git rev-parse --abbrev-ref --symbolic-full-name '@{u}' >/dev/null 2>&1; then
  echo "[safe_sync] Pushing to upstream ..."
  git push
else
  echo "[safe_sync] No upstream configured. Pushing with -u origin ${BRANCH} ..."
  git push -u origin "${BRANCH}"
fi

echo "[safe_sync] Done."
