#!/usr/bin/env bash
# Run the test suite, starting and stopping the dev server as needed.
# All arguments are passed through to testit.py.
#
# Usage:
#   ./bin/run_tests                  # run all tests
#   ./bin/run_tests -t test_accounts # run a specific module
#   ./bin/run_tests -s               # stop on first failure

set -euo pipefail

# Ensure Homebrew and common tool paths are available
export PATH="/opt/homebrew/bin:/usr/local/bin:$PATH"

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Load .env from repo root if present (secrets like LLM_HANDLER_API_KEY)
if [ -f "$REPO_ROOT/.env" ]; then
    set -a
    source "$REPO_ROOT/.env"
    set +a
fi

# Isolate the test process from the developer's real AWS (maestro #2789) —
# same block as bin/asgi_local, which covers the server side. Env credentials
# are boto's first chain leg and .env was just sourced; a stale AWS_PROFILE
# raises ProfileNotFound instead of falling through. Tests seed AWS access
# through mojo-level Setting rows only.
export AWS_SHARED_CREDENTIALS_FILE=/dev/null
export AWS_CONFIG_FILE=/dev/null
export AWS_EC2_METADATA_DISABLED=true
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE AWS_DEFAULT_PROFILE 2>/dev/null || true
# Container (ECS/Fargate) and web-identity (IRSA) chain legs need no config
# file and are not IMDS — clear them too or a CI runner still resolves creds.
unset AWS_CONTAINER_CREDENTIALS_RELATIVE_URI AWS_CONTAINER_CREDENTIALS_FULL_URI AWS_CONTAINER_AUTHORIZATION_TOKEN AWS_WEB_IDENTITY_TOKEN_FILE AWS_ROLE_ARN 2>/dev/null || true

# Start server if not already running; track so we know to stop it after
STARTED_SERVER=0
if ! "$SCRIPT_DIR/asgi_local" status | grep -q "Running"; then
    "$SCRIPT_DIR/asgi_local" start
    # Poll for readiness instead of a fixed sleep (maestro #2789): the old
    # `sleep 3` was both too long (app construction is ~1s) and unsafe (no
    # check at all). `wait` fails loudly after 30s.
    if ! "$SCRIPT_DIR/asgi_local" wait; then
        # Don't orphan the daemon we just started (set -e would exit here).
        "$SCRIPT_DIR/asgi_local" stop
        exit 1
    fi
    STARTED_SERVER=1
fi

# Run tests — capture exit code so we always stop the server
EXIT_CODE=0
# --frozen: run against uv.lock as it stands, never rewrite it. The lock
# carries this package's own version (source = { editable = "." }), so after
# publish.py bumps pyproject.toml a plain `uv run` re-syncs and rewrites that
# line — every test run after a release left the tree dirty in a file nobody
# touched. publish.py now re-locks at release time, which is the only place
# the lock should move. A dependency added to pyproject.toml without a
# `uv lock` will fail here with an ImportError; that is the intended trade.
uv run --frozen "$SCRIPT_DIR/testit.py" "$@" || EXIT_CODE=$?

if [ "$STARTED_SERVER" -eq 1 ]; then
    "$SCRIPT_DIR/asgi_local" stop
fi

exit $EXIT_CODE
