#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(git rev-parse --show-toplevel)"
cd "${ROOT_DIR}"

HOOK_NAME="tonbo pre-commit"
S3_ENV_SCRIPT="${ROOT_DIR}/tests/s3_localstack_env.sh"

log() {
  echo "[${HOOK_NAME}] $1"
}

if ! command -v cargo >/dev/null 2>&1; then
  echo "[${HOOK_NAME}] skipping: cargo not found" >&2
  exit 0
fi

if ! command -v rustup >/dev/null 2>&1; then
  echo "[${HOOK_NAME}] rustup not detected; install rustup and the nightly toolchain" >&2
  exit 1
fi

if ! rustup toolchain list | grep -q "nightly"; then
  echo "[${HOOK_NAME}] nightly toolchain required (rustup toolchain install nightly)" >&2
  exit 1
fi

if ! command -v cargo-llvm-cov >/dev/null 2>&1; then
  echo "[${HOOK_NAME}] cargo-llvm-cov required (cargo install cargo-llvm-cov)" >&2
  exit 1
fi

ACTIVE_TOOLCHAIN="$(rustup show active-toolchain | awk '{print $1}')"
if ! rustup component list --toolchain "${ACTIVE_TOOLCHAIN}" | grep -q "llvm-tools"; then
  echo "[${HOOK_NAME}] llvm-tools required (rustup component add llvm-tools --toolchain ${ACTIVE_TOOLCHAIN})" >&2
  echo "[${HOOK_NAME}] if your toolchain only offers llvm-tools-preview, install it instead." >&2
  exit 1
fi

FMT_CHECK_CMD="cargo +nightly fmt --all -- --check"
CLIPPY_CMD="cargo clippy --workspace -- -D warnings"
BUILD_CMD="cargo build --verbose"
TEST_CMD="cargo test --verbose"
COVERAGE_LINES_MIN="${COVERAGE_LINES_MIN:-80}"
COVERAGE_DIR="target/coverage"
COVERAGE_CMD="cargo llvm-cov --workspace --lcov --output-path ${COVERAGE_DIR}/lcov.info --fail-under-lines ${COVERAGE_LINES_MIN}"

run_step() {
  local cmd="$1"
  log "$cmd"
  if ! eval "$cmd"; then
    echo "[${HOOK_NAME}] command failed: $cmd" >&2
    if [[ "$cmd" == "$FMT_CHECK_CMD" ]]; then
      echo "[${HOOK_NAME}] run 'cargo +nightly fmt --all' to apply formatting and re-stage changes before committing." >&2
    fi
    exit 1
  fi
}

run_step "$FMT_CHECK_CMD"
run_step "$CLIPPY_CMD"
run_step "$BUILD_CMD"
run_step "$TEST_CMD"
mkdir -p "${COVERAGE_DIR}"
run_step "$COVERAGE_CMD"

log "bootstrap LocalStack (if available) for S3-backed public_api_e2e"
if source "${S3_ENV_SCRIPT}"; then
  run_step "cargo test public_api_e2e:: -- --nocapture"
  if [ "${TONBO_LOCALSTACK_STARTED_BY_SCRIPT:-0}" = "1" ] && command -v docker >/dev/null 2>&1; then
    docker rm -f "${TONBO_LOCALSTACK_CONTAINER}" >/dev/null 2>&1 || true
  fi
else
  log "LocalStack not available; running public_api_e2e (local only)"
  run_step "cargo test public_api_e2e:: -- --nocapture"
fi

exit 0
