#!/usr/bin/env bash
# Copyright 2026 ddbsh reimplementation contributors.
# SPDX-License-Identifier: Apache-2.0
#
# devtools/run-tests — code-repo test entry point.
#
# Runs the CTest golden suite against REAL DynamoDB (us-east-1) using the
# standard AWS resolution chain (~/.aws credentials/config, AWS_PROFILE,
# AWS_REGION). No endpoint override is used; DynamoDB Local and extenddb are not
# used (human decisions 2026-08-17/22).
#
# Step-2 exit gate (2h-1, 2026-10-19): the golden family route is COMPLETE.
# Every family runs against the NEW engine (the shipping `ddbsh` binary driven
# through the external harness in tests/golden/). The 2b two-sub-run scaffold
# (routed families on the new engine, the complement on the original C++11
# engine) is retired: there is one engine build, one golden registration (all
# families, including the real multi-region global-tables family un-deferred in
# phase 2j), and the gate exit propagates. The old C++11 engine was removed from
# the working tree during the phase-2i oracle retirement (preserved in git
# history under the oracle-archive-v0.8.1 tag); the golden contract it came with
# was relocated out of oracle/ and consolidated into a single command-family
# tree at tests/golden/ (families/ manifests, results/ goldens, data/ .sql
# seeds, ddbsh-wait) and is the sole surviving artifact.
#
# The native GoogleTest suite (offline, FakeDDBClient) runs alongside as the
# deterministic backend-free fidelity signal; a native failure fails the gate.
#
# The test target (endpoint + access key id) is echoed and verified before any
# test runs. Two artifacts are written into this repo's discussions/ directory,
# named by the current HEAD short hash so they are tracked in version control
# and copied back by the orchestration repo's devtools/run-tests:
#
#   discussions/test-<suite>-<HEAD-short>.log   full ctest output (both sub-runs)
#   discussions/test-<suite>-<HEAD-short>.txt   summary (target + combined counts)
#
# Usage:
#   devtools/run-tests                     # full suite (label: all)
#   devtools/run-tests -R isel             # ctest regex filter (label derived)
#   devtools/run-tests --suite select -R isel
#   devtools/run-tests --full-engine       # route EVERY family to the new engine
#   devtools/run-tests --web-golden        # the golden suite through the
#                                          # browser edition (devtools/run-web-golden)
#   devtools/run-tests --web-smoke         # the browser edition's quick gates
#                                          # (devtools/run-web-smoke)
#   devtools/run-tests --python            # the Python package's gates: offline
#                                          # and live pytest, and the golden
#                                          # suite through `python -m ddbsh`
#                                          # (devtools/run-python-golden)
#   devtools/run-tests --live-sample       # also build + run the live embedding
#                                          # tests (opt-in; creates a real table)
#   devtools/run-tests --build-only        # build build-engine/ddbsh and
#                                          # configure build-golden exactly as a
#                                          # full run does, then exit 0: no AWS
#                                          # call, no target echo, no artifact
#                                          # (CI builds before any credential
#                                          # exists on the runner, D-P11-28)
#   devtools/run-tests --help              # print this usage and exit; builds,
#                                          # runs and writes nothing (also -h)
#   AWS_PROFILE=p AWS_REGION=us-east-1 devtools/run-tests
#
# Modes:
#   default        every family runs on the new engine (including the real
#                  multi-region global-tables family as of phase 2j); the gate
#                  exit propagates (a golden or native failure fails the run).
#                  This is the phase gate.
#   --full-engine  same registration (all families on the new engine), but a
#                  MEASUREMENT: the exit code is forced to 0 so the parity
#                  figure is read from the printed counts / artifact rather than
#                  the gate. Retained from the 2a exposure mode (D-2a-3) for
#                  measurement runs; since 2h-1 it registers the same families as
#                  the default gate and differs only in exit semantics.
#
# Env overrides: DDBSH_ENGINE_BUILD_DIR, DDBSH_GOLDEN_BUILD_DIR, DDBSH_SDK_PREFIX,
# DDBSH_SDK_LIB, CC/CXX.
#
# DDBSH_REDACT_KEY_ID=1 shows the access key id in the golden run's target echo
# only by its first and last four characters (ASIA…WXYZ). CI sets it, because
# anyone signed in to GitHub can read its artifacts (DEV-P11-12). Unset, empty
# or 0 shows the whole id, as local runs do; any other value is refused. The web
# gates (--web-golden, --web-smoke) always show the minted id whole.
#
# WARNING: this talks to a real AWS account. create/insert/update/delete/drop
# operate on real tables and data, incur real cost, and are irreversible. Use a
# dedicated test account/region.

set -euo pipefail

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

# Print the header comment from "Usage:" to its end (Usage, Modes, Env
# overrides, WARNING) without the leading "# ".
usage() {
    sed -n '/^# Usage:/,/^$/{s/^# \{0,1\}//;p;}' "${BASH_SOURCE[0]}"
}

# --- Argument parsing -------------------------------------------------------
# Optional --suite <label>; --full-engine selects the exposure mode; all other
# args pass through to ctest. -h / --help print the usage and exit 0 before
# anything is built, echoed or written: passed through to ctest, `--help` ran no
# test but still wrote this HEAD's summary artifact over the real one (P10 N21).
SUITE=""
FULL_ENGINE=0
# --live-sample (opt-in): additionally build + run the LIVE embedding tests —
# the examples/ddbshlib_sample demo CTest (ddbshlib_sample) as an external
# find_package(ddbsh) consumer, and the real-DDB functional test
# (ddbsh_live_api) — against real DynamoDB. OFF by default — it SPENDS
# (creates+drops a real table) and
# needs credentials, so the default gate never builds or runs it. When set, it
# configures the native build with -DDDBSH_TEST_LIVE_SAMPLE=ON so the sample is
# registered and runs alongside the native suite (D8).
LIVE_SAMPLE=0
# --web-golden: run the browser edition's fidelity gate instead (P9,
# D-P9-02-4): the whole golden suite through ddbsh.wasm + the AWS SDK for
# JavaScript, via devtools/run-web-golden. Remaining args go to ctest. Its
# artifacts are discussions/test-webgolden-<hash>.{log,txt}.
WEB_GOLDEN=0
# --web-smoke: run the browser edition's quick gates instead (P9 §4.5): wasm
# build, offline web gates, storage grep gate and the live UI-path smoke, via
# devtools/run-web-smoke. Takes no further args. Its artifact is
# discussions/test-websmoke-<hash>.log.
WEB_SMOKE=0
# --python: run the Python package's gates instead (P13 T3): build the wheel
# into a virtualenv, run the offline and live pytest suites, and the whole
# golden suite through `python -m ddbsh`, via devtools/run-python-golden.
# Remaining args go to ctest. Its artifacts are
# discussions/test-python-<hash>.{log,txt}.
PYTHON_GATE=0
# --build-only (D-P11-28): build the CLI and configure the golden project, then
# stop before the target echo. Takes no further args.
BUILD_ONLY=0
CTEST_ARGS=()
while [ $# -gt 0 ]; do
    case "$1" in
        --suite)
            SUITE="${2:-}"
            shift 2
            ;;
        --full-engine)
            FULL_ENGINE=1
            shift
            ;;
        --live-sample)
            LIVE_SAMPLE=1
            shift
            ;;
        --web-golden)
            WEB_GOLDEN=1
            shift
            ;;
        --web-smoke)
            WEB_SMOKE=1
            shift
            ;;
        --python)
            PYTHON_GATE=1
            shift
            ;;
        --build-only)
            BUILD_ONLY=1
            shift
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        *)
            CTEST_ARGS+=("$1")
            shift
            ;;
    esac
done

# DDBSH_REDACT_KEY_ID (DEV-P11-12): 1 shortens the access key id in the target
# echo; unset, empty or 0 shows it whole. Checked before anything is built, and
# any other value is refused, so a typo cannot show the whole id where it was
# meant to be hidden.
REDACT_KEY_ID="${DDBSH_REDACT_KEY_ID:-0}"
if [ "$REDACT_KEY_ID" != "0" ] && [ "$REDACT_KEY_ID" != "1" ]; then
    echo "error: DDBSH_REDACT_KEY_ID must be 0 or 1 (got: $REDACT_KEY_ID)." >&2
    exit 2
fi

if [ "$BUILD_ONLY" -eq 1 ]; then
    if [ "${#CTEST_ARGS[@]}" -gt 0 ] || [ -n "$SUITE" ] || [ "$FULL_ENGINE" -eq 1 ] ||
       [ "$LIVE_SAMPLE" -eq 1 ] || [ "$WEB_GOLDEN" -eq 1 ] || [ "$WEB_SMOKE" -eq 1 ] ||
       [ "$PYTHON_GATE" -eq 1 ]; then
        echo "error: --build-only takes no further arguments." >&2
        exit 2
    fi
fi

if [ $((WEB_GOLDEN + WEB_SMOKE + PYTHON_GATE)) -gt 1 ]; then
    echo "error: --web-golden, --web-smoke and --python are separate runs; pass one." >&2
    exit 2
fi
if [ "$PYTHON_GATE" -eq 1 ]; then
    exec "$REPO_DIR/devtools/run-python-golden" ${CTEST_ARGS[@]+"${CTEST_ARGS[@]}"}
fi
if [ "$WEB_SMOKE" -eq 1 ]; then
    if [ "${#CTEST_ARGS[@]}" -gt 0 ]; then
        echo "error: --web-smoke takes no further arguments (got: ${CTEST_ARGS[*]})." >&2
        exit 2
    fi
    exec "$REPO_DIR/devtools/run-web-smoke"
fi
if [ "$WEB_GOLDEN" -eq 1 ]; then
    exec "$REPO_DIR/devtools/run-web-golden" ${CTEST_ARGS[@]+"${CTEST_ARGS[@]}"}
fi

# The native and web golden suites share the ddbsh_test_* tables in one
# account; hold the shared lock so they never overlap (devtools/lib-web.sh).
# shellcheck source=devtools/lib-web.sh
. "$REPO_DIR/devtools/lib-web.sh"
web_golden_lock "$REPO_DIR"

# Derive a suite label if not given: use the -R regex if present, else "all"
# ("full-engine" in exposure mode).
if [ -z "$SUITE" ]; then
    for ((i = 0; i < ${#CTEST_ARGS[@]}; i++)); do
        if [ "${CTEST_ARGS[$i]}" = "-R" ]; then
            SUITE="${CTEST_ARGS[$((i + 1))]:-all}"
            break
        fi
    done
fi
if [ -z "$SUITE" ]; then
    if [ "$FULL_ENGINE" -eq 1 ]; then SUITE="full-engine"; else SUITE="all"; fi
fi
# Sanitize the label for use in a filename.
SUITE="$(printf '%s' "$SUITE" | tr -c 'A-Za-z0-9._-' '-')"

# --- Repo / build resolution ------------------------------------------------
HASH="$(cd "$REPO_DIR" && git rev-parse --short HEAD 2>/dev/null || echo unknown)"
# The golden contract (family .txt files, results/*.exp goldens, .sql seeds,
# ddbsh-wait) was relocated out of oracle/ during the phase-2i oracle retirement
# (the old C++11 engine it came with was removed; see the oracle-archive-v0.8.1
# git tag) and consolidated into a single command-family tree at
# tests/golden/ during phase 2j (AI-2j-5). It is consumed by the golden harness
# via -DGOLDEN_DIR below.
GOLDEN_DIR_PATH="$REPO_DIR/tests/golden"
DISCUSSIONS_DIR="$REPO_DIR/discussions"
mkdir -p "$DISCUSSIONS_DIR"

LOG_FILE="$DISCUSSIONS_DIR/test-${SUITE}-${HASH}.log"
SUMMARY_FILE="$DISCUSSIONS_DIR/test-${SUITE}-${HASH}.txt"

# AWS SDK install prefix (where AWSSDKConfig.cmake / the libs live). The oracle
# CMake resolves the SDK via find_package(AWSSDK), so first-time configure must
# be told the prefix; overridable via DDBSH_SDK_PREFIX.
DDBSH_SDK_PREFIX="${DDBSH_SDK_PREFIX:-$HOME/.local/aws-sdk-cpp}"
# Compiler: the prebuilt AWS SDK was compiled with gcc14; the new engine must
# link against it with the same toolchain (default cc/c++ = gcc 11 fails to
# resolve __cxa_call_terminate against the gcc14-built CRT static libs).
# Overridable via CC/CXX for other environments.
DDBSH_CC="${CC:-gcc14-gcc}"
DDBSH_CXX="${CXX:-gcc14-g++}"
# AWS SDK shared libraries (mirrors devtools/ddbsh-aws in the orchestration repo).
export LD_LIBRARY_PATH="${DDBSH_SDK_LIB:-$DDBSH_SDK_PREFIX/lib64}${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
# Prefer the regional STS endpoint (the legacy global endpoint is disabled on
# some accounts; cross-account AssumeRole tests need this).
export AWS_STS_REGIONAL_ENDPOINTS="${AWS_STS_REGIONAL_ENDPOINTS:-regional}"

REGION="${AWS_REGION:-${AWS_DEFAULT_REGION:-us-east-1}}"
export AWS_REGION="$REGION"

# --- Golden suite wiring (2h-1 exit gate) -----------------------------------
# The route is complete: every family runs on the new engine (the shipping
# `ddbsh` binary driven through the external harness in tests/golden/). There is
# no oracle sub-run and no routed/complement split. As of phase 2j the
# global-tables family (real multi-region: primary us-east-2, replica us-west-1)
# is included too (AI-2j-2), gated by region-aware ddbsh-wait settling polls.
ENGINE_SRC="$REPO_DIR"
ENGINE_BUILD="${DDBSH_ENGINE_BUILD_DIR:-$REPO_DIR/build-engine}"
GOLDEN_SRC="$REPO_DIR/tests/golden"
GOLDEN_BUILD="${DDBSH_GOLDEN_BUILD_DIR:-$REPO_DIR/build-golden}"
DDBSH_SDK_LIB="${DDBSH_SDK_LIB:-$DDBSH_SDK_PREFIX/lib64}"

# --- Build: new engine (runs every family via the golden harness) -----------
if [ ! -f "$ENGINE_BUILD/CMakeCache.txt" ]; then
    echo "=== Configuring new-engine build (no CMakeCache at $ENGINE_BUILD) ==="
    cmake -S "$ENGINE_SRC" -B "$ENGINE_BUILD" \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_PREFIX_PATH="$DDBSH_SDK_PREFIX" \
        -DCMAKE_C_COMPILER="$DDBSH_CC" \
        -DCMAKE_CXX_COMPILER="$DDBSH_CXX" \
        -DDDBSH_BUILD_TESTS=OFF
fi
echo "=== Building new-engine ddbsh CLI ($HASH) ==="
cmake --build "$ENGINE_BUILD" --target ddbsh-cli

ENGINE_BIN="$ENGINE_BUILD/ddbsh"
if [ ! -x "$ENGINE_BIN" ]; then
    echo "error: $ENGINE_BIN not found after build." >&2
    exit 1
fi

# --- Configure: golden parity project (drives the relocated golden suite) ---
echo "=== Configuring golden-parity project (all families -> new engine) ==="
cmake -S "$GOLDEN_SRC" -B "$GOLDEN_BUILD" \
    -DDDBSH_SHELL_BIN="$ENGINE_BIN" \
    -DDDBSH_SDK_LIB="$DDBSH_SDK_LIB" \
    -DGOLDEN_DIR="$GOLDEN_DIR_PATH"

if [ "$BUILD_ONLY" -eq 1 ]; then
    echo "=== Build only ($HASH): built $ENGINE_BIN, configured $GOLDEN_BUILD; no AWS call, no artifact ==="
    exit 0
fi

# --- Target echo + verification ---------------------------------------------
# No endpoint override => the real regional DynamoDB endpoint.
ENDPOINT="dynamodb.${REGION}.amazonaws.com (real DynamoDB, no override)"
ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID:-$(aws configure get aws_access_key_id 2>/dev/null || true)}"
[ -z "$ACCESS_KEY_ID" ] && ACCESS_KEY_ID="(unresolved)"
# What the echo shows: the whole id, or with DDBSH_REDACT_KEY_ID=1 its 4-character
# prefix and last four characters, the form the browser edition's SHOW
# CONNECTION uses (web/app-core.mjs, maskAccessKeyId).
ACCESS_KEY_SHOWN="$ACCESS_KEY_ID"
if [ "$REDACT_KEY_ID" = "1" ] && [ "$ACCESS_KEY_ID" != "(unresolved)" ]; then
    if [ "${#ACCESS_KEY_ID}" -gt 8 ]; then
        ACCESS_KEY_SHOWN="${ACCESS_KEY_ID:0:4}…${ACCESS_KEY_ID: -4} (shortened: DDBSH_REDACT_KEY_ID=1)"
    else
        ACCESS_KEY_SHOWN="… (shortened: DDBSH_REDACT_KEY_ID=1)"
    fi
fi
CALLER_ARN="$(aws sts get-caller-identity --query Arn --output text --region "$REGION" 2>/dev/null || echo '(sts unavailable)')"

{
    echo "ddbsh test run"
    echo "  commit:        $HASH"
    echo "  suite:         $SUITE"
    echo "  timestamp:     $(date -u +%Y-%m-%dT%H:%M:%SZ)"
    echo "  region:        $REGION"
    echo "  endpoint:      $ENDPOINT"
    echo "  access key id: $ACCESS_KEY_SHOWN"
    echo "  caller arn:    $CALLER_ARN"
} | tee "$SUMMARY_FILE"

if [ "$ACCESS_KEY_ID" = "(unresolved)" ]; then
    echo "error: could not resolve an AWS access key id; refusing to run against an unknown target." >&2
    echo "  provide credentials via ~/.aws or AWS_ACCESS_KEY_ID/AWS_PROFILE." | tee -a "$SUMMARY_FILE" >&2
    exit 1
fi

# --- Run --------------------------------------------------------------------
# A single golden run: every family on the new engine via the harness
# (including the global-tables family as of phase 2j). CTEST_ARGS (e.g. -R isel)
# filter the registered set. The pass/fail is the suite result (unless
# --full-engine forces RC=0 as a measurement).
ENGINE_LOG="${LOG_FILE%.log}-engine.log"

echo "=== Running golden families on the new engine ===" | tee -a "$SUMMARY_FILE"
set +e
ctest --test-dir "$GOLDEN_BUILD" --output-on-failure \
    ${CTEST_ARGS[@]+"${CTEST_ARGS[@]}"} 2>&1 | tee "$ENGINE_LOG"
RC_ENGINE=${PIPESTATUS[0]}
set -e

# Extract counts from the golden log. ctest prints
# "<pct>% tests passed, <F> tests failed out of <N>", so passed = N - F. This
# tolerates a run with no summary line without aborting under set -e.
counts() {
    # $1 = ctest log file; echoes "<passed> <total>"
    local line out failed
    line="$(grep -E "tests passed|tests failed" "$1" 2>/dev/null | tail -1 || true)"
    out="$(grep -oE "out of [0-9]+" <<<"$line" 2>/dev/null | grep -oE "[0-9]+" || true)"
    failed="$(grep -oE "[0-9]+ tests failed" <<<"$line" 2>/dev/null | grep -oE "[0-9]+" || true)"
    out=${out:-0}
    failed=${failed:-0}
    echo "$((out - failed)) $out"
}
read -r e_pass e_out < <(counts "$ENGINE_LOG")

# --- Native unit tests (AI-2d-B): offline GoogleTest suite ------------------
# The native suite (GoogleTest, FakeDDBClient) is the deterministic, backend-
# free fidelity signal (EXPLAIN alias numbering, request-shape assertions,
# reentrancy). Before 2d it produced NO tracked artifact, which let the
# f232b74 version-rot slip past artifact-based review (2c principal process
# gap). It now builds + runs on every gate invocation and writes a HEAD-matched
# artifact alongside the golden one, and a native failure propagates to the
# gate exit code. It is offline (no AWS), so it runs regardless of the backend
# target. Set DDBSH_SKIP_NATIVE=1 to skip (e.g. a golden-only -R filter run).
NATIVE_PASS=0
NATIVE_OUT=0
RC_NATIVE=0
if [ "${DDBSH_SKIP_NATIVE:-0}" -eq 0 ]; then
    NATIVE_BUILD="${DDBSH_NATIVE_BUILD_DIR:-$REPO_DIR/build-unit}"
    NATIVE_LOG="$DISCUSSIONS_DIR/test-native-${HASH}.log"
    echo "=== Configuring + building native unit tests ($HASH) ===" | tee -a "$SUMMARY_FILE"
    NATIVE_CFG=(-DCMAKE_BUILD_TYPE=Debug
                -DCMAKE_PREFIX_PATH="$DDBSH_SDK_PREFIX"
                -DCMAKE_C_COMPILER="$DDBSH_CC"
                -DCMAKE_CXX_COMPILER="$DDBSH_CXX")
    if [ "$LIVE_SAMPLE" -eq 1 ]; then
        # Register the LIVE example + functional CTests (opt-in; they spend).
        NATIVE_CFG+=(-DDDBSH_TEST_LIVE_SAMPLE=ON)
    fi
    # Reconfigure when there is no cache OR when --live-sample is requested (the
    # flag must take effect even on a pre-existing cache).
    if [ ! -f "$NATIVE_BUILD/CMakeCache.txt" ] || [ "$LIVE_SAMPLE" -eq 1 ]; then
        cmake -S "$ENGINE_SRC" -B "$NATIVE_BUILD" "${NATIVE_CFG[@]}"
    fi
    if [ "$LIVE_SAMPLE" -eq 1 ]; then
        # The live sample installs from this build dir, so the engine + the AWS
        # component must be built (not just the test binary).
        cmake --build "$NATIVE_BUILD"
    else
        cmake --build "$NATIVE_BUILD" --target ddbsh-tests
    fi
    echo "=== Running native unit tests ($HASH) ===" | tee -a "$SUMMARY_FILE"
    set +e
    ctest --test-dir "$NATIVE_BUILD" --output-on-failure 2>&1 | tee "$NATIVE_LOG"
    RC_NATIVE=${PIPESTATUS[0]}
    set -e
    read -r NATIVE_PASS NATIVE_OUT < <(counts "$NATIVE_LOG")
    echo "=== Native unit tests: ${NATIVE_PASS}/${NATIVE_OUT} passed ===" | tee -a "$SUMMARY_FILE"
    echo "  $NATIVE_LOG"
fi

# Promote the golden log to the canonical artifact (single run; no oracle side).
mv -f "$ENGINE_LOG" "$LOG_FILE"

RC=0
# ctest exit code 8 was historically treated here as "no tests were found" and
# benign. EMPIRICAL CORRECTION (AI-2c-B, 2026-10-18): `ctest -R <no-match>`
# returns 0, not 8 — exit 8 actually means a test FAILED. The old benign(8)
# therefore MASKED real failures in the gate's exit code. Fixed: only 0 is
# success, so a real failure propagates to the process exit code (the printed
# counts below remain the human-readable source of truth either way).
benign() { [ "$1" -eq 0 ]; }
benign "$RC_ENGINE" || RC=$RC_ENGINE
# A native unit-test failure is a gate failure (AI-2d-B): the native suite is
# the deterministic fidelity signal, so a regression there must not pass the
# gate even if the golden families are green.
benign "$RC_NATIVE" || RC=$RC_NATIVE
# Full-engine is a MEASUREMENT, not a gate: it always exits 0 explicitly (the
# parity figure is read from the printed counts / artifact, not the exit code).
# Since 2h-1 it registers the same families as the default gate; the only
# difference is this forced-zero exit.
[ "$FULL_ENGINE" -eq 1 ] && RC=0

{
    echo ""
    echo "=== ctest summary ==="
    echo "  golden (new engine):  ${e_pass}/${e_out} passed"
    echo "  native unit tests:    ${NATIVE_PASS}/${NATIVE_OUT} passed"
    echo "  combined:             $((e_pass + NATIVE_PASS))/$((e_out + NATIVE_OUT)) passed"
    grep -E "Total Test time|Errors while running CTest" "$LOG_FILE" || true
    echo ""
    echo "ctest exit codes: golden=$RC_ENGINE native=$RC_NATIVE (combined=$RC)"
} | tee -a "$SUMMARY_FILE"

echo "=== Artifacts ==="
echo "  $LOG_FILE"
echo "  $SUMMARY_FILE"

exit $RC
