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

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

PYTHON_BIN="${PYTHON_BIN:-python}"
export PYTHONPATH="${ROOT_DIR}/src"

echo "[ci-local] ruff"
"$PYTHON_BIN" -m ruff check src tests

echo "[ci-local] mypy"
"$PYTHON_BIN" -m mypy

echo "[ci-local] unit tests + coverage"
"$PYTHON_BIN" -m pytest -q -m "not integration" \
  --cov=kyrodb \
  --cov-branch \
  --cov-report=term-missing \
  --cov-report=json
"$PYTHON_BIN" scripts/check_coverage_thresholds.py

echo "[ci-local] docs lint"
"$PYTHON_BIN" scripts/check_docs_links.py

echo "[ci-local] examples smoke"
"$PYTHON_BIN" -m pytest -q tests/test_examples.py

echo "[ci-local] build artifacts"
"$PYTHON_BIN" -m build

echo "[ci-local] twine check"
"$PYTHON_BIN" -m twine check dist/*.whl dist/*.tar.gz

if "$PYTHON_BIN" -m pip_audit --version >/dev/null 2>&1; then
  echo "[ci-local] pip-audit"
  "$PYTHON_BIN" -m pip_audit --strict --cache-dir /tmp/pip-audit-cache .
else
  echo "[ci-local] pip-audit not installed; skipping"
fi

if [[ -z "${KYRODB_SERVER_BIN:-}" ]]; then
  CORE_ROOT="$(cd "$ROOT_DIR/.." && pwd)"
  if [[ -f "$CORE_ROOT/Cargo.toml" && -f "$CORE_ROOT/engine/Cargo.toml" ]]; then
    echo "[ci-local] KYRODB_SERVER_BIN not set; building kyrodb_server from $CORE_ROOT"
    (cd "$CORE_ROOT" && cargo build --release -p kyrodb-engine --bin kyrodb_server)
    KYRODB_SERVER_BIN="$CORE_ROOT/target/release/kyrodb_server"
    export KYRODB_SERVER_BIN
  fi
fi

if [[ -n "${KYRODB_SERVER_BIN:-}" && -x "${KYRODB_SERVER_BIN}" ]]; then
  echo "[ci-local] integration tests (live server)"
  "$PYTHON_BIN" -m pytest -q -m integration tests/integration
else
  echo "[ci-local] KYRODB_SERVER_BIN not set/executable; skipping integration tests"
fi

echo "[ci-local] done"
