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

HOOK_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$HOOK_DIR/.." && pwd)"

cd "$REPO_ROOT"

# =============================================================================
# Go CI checks (when .go files are staged)
# =============================================================================
STAGED_GO_FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep '\.go$' || true)

if [[ -n "$STAGED_GO_FILES" ]]; then
  echo "Go files staged, running CI checks..."

  # Format check
  echo "  Checking gofmt..."
  UNFORMATTED=$(gofmt -s -l . 2>/dev/null || true)
  if [[ -n "$UNFORMATTED" ]]; then
    echo "The following files are not formatted:"
    echo "$UNFORMATTED"
    echo ""
    echo "Run: cd core && gofmt -s -w ."
    exit 1
  fi

  # golangci-lint
  if command -v golangci-lint &>/dev/null; then
    echo "  Running golangci-lint..."
    golangci-lint run ./...
  else
    echo "  Warning: golangci-lint not installed, skipping lint"
    echo "  Install: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest"
  fi

  # Tests
  echo "  Running tests..."
  if ! go test ./... >/dev/null 2>&1; then
    echo "Tests failed! Run 'go test ./...' for details."
    exit 1
  fi

  # Build check
  echo "  Building..."
  mkdir -p bin
  go build -buildvcs=false -o bin/dsearch ./cmd/dsearch

  echo "All Go CI checks passed!"
fi

# =============================================================================
# i18n sync check (DISABLED for now)
# =============================================================================
# if [[ -n "${POEDITOR_API_TOKEN:-}" ]] && [[ -n "${POEDITOR_PROJECT_ID:-}" ]]; then
#     if command -v python3 &>/dev/null; then
#         if ! python3 scripts/i18nsync.py check &>/dev/null; then
#             echo "Translations out of sync"
#             echo "Run: python3 scripts/i18nsync.py sync"
#             exit 1
#         fi
#     fi
# fi

exit 0
