#!/usr/bin/env bash
#
# Test runner — "Does the code work?"
#
# Usage:
#   ./scripts/test.sh                        # Run all tests on real K8s (default)
#   ./scripts/test.sh --backend fake         # Run all tests on fake backend only
#   ./scripts/test.sh --backend real         # Run all tests on real K8s (explicit)
#   ./scripts/test.sh tests/apps/            # Run specific module (fake only)
#   ./scripts/test.sh -k test_create         # Run tests matching pattern
#   ./scripts/test.sh --no-cov               # Skip coverage report
#   ./scripts/test.sh --slow                 # Include slow tests (addon lifecycle, versioning)
#

source "$(dirname "$0")/_common.sh"

printf "Python: %s\n" "$PY"

# Parse test-specific args
COV=true
BACKEND=""
RUNSLOW=""
PYTEST_ARGS=()
for arg in "$@"; do
    if [ "$arg" = "--no-cov" ]; then
        COV=false
    elif [ "$arg" = "--fix" ]; then
        continue
    elif [ "$arg" = "--slow" ]; then
        RUNSLOW=1
    elif [ "$arg" = "--backend" ]; then
        BACKEND="__next__"
    elif [ "$BACKEND" = "__next__" ]; then
        BACKEND="$arg"
    else
        PYTEST_ARGS+=("$arg")
    fi
done

# ── Coverage args ──────────────────────────────────────────────
if [ "$COV" = true ]; then
    COV_ARGS=(--cov=kuberoku --cov-report=term-missing --cov-config=pyproject.toml)
else
    COV_ARGS=()
fi

# ── Backend logic ──────────────────────────────────────────────
# Default: run real (requires K8s cluster)
# --backend fake: run all tests on fake only
# --backend real: run all tests on real K8s

run_fake() {
    section "Tests (fake backend)"
    if [ "${#PYTEST_ARGS[@]}" -gt 0 ]; then
        "$PY" -m pytest ${COV_ARGS[@]+"${COV_ARGS[@]}"} --backend fake "${PYTEST_ARGS[@]}" && pass "pytest (fake)" || fail "pytest (fake)"
    else
        "$PY" -m pytest ${COV_ARGS[@]+"${COV_ARGS[@]}"} --backend fake tests/ -v && pass "pytest (fake)" || fail "pytest (fake)"
    fi
}

run_real() {
    section "Tests (real backend)"
    if ! kubectl cluster-info &> /dev/null; then
        skip "pytest (real)" "no K8s cluster available"
        return
    fi
    "$PY" -m pytest --backend real tests/ -v -n4 --dist loadfile ${RUNSLOW:+--runslow} && pass "pytest (real)" || fail "pytest (real)"
}

case "$BACKEND" in
    fake)
        run_fake
        ;;
    real)
        run_real
        ;;
    "")
        run_real
        ;;
    *)
        printf "Unknown backend: %s (use fake or real)\n" "$BACKEND"
        exit 1
        ;;
esac

summary
