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

# Run the peddlers-test harness while streaming the server container logs to
# a timestamped file in the repo root. This helps correlate client-side
# intercepted WS sends with server handling (e.g., setPlayerName lines).

# Use a YYMMDD-HHMMSS style run dir name so it lines up with the harness.
RUN_DIR_NAME=$(date +"%y%m%d-%H%M%S")
TS=$(date +%s)
OUT_DIR=$(pwd)
# Per-run directories live under test-output/<run-dir>
mkdir -p "$OUT_DIR/test-output"
LOGDIR="$OUT_DIR/test-output/${RUN_DIR_NAME}"
mkdir -p "$LOGDIR"
LOGFILE="$LOGDIR/server-logs-$TS.server.log"
echo "ts=$TS run_dir=$RUN_DIR_NAME"

# Find the server container by common names used in docker-compose
CID=$(docker ps -q --filter "name=ketr.ketran.dev" || true)
if [ -z "$CID" ]; then CID=$(docker ps -q --filter "name=ketr.ketran" || true); fi
if [ -z "$CID" ]; then
  # fallback: try to find the compose service container
  CID=$(docker compose -f docker-compose.yml ps -q peddlers-of-ketran || true)
fi
echo "server container id: ${CID:-<none>}"

LOG_PID=""
  if [ -n "$CID" ]; then
  echo "Starting log follower: docker logs -f $CID -> $LOGFILE"
  # Stream logs (since 0s to include recent lines) in background
  docker logs --since 0s -f "$CID" > "$LOGFILE" 2>&1 &
  LOG_PID=$!
  echo "log follower pid: $LOG_PID"
else
  echo "Warning: no server container found; server logs will not be captured"
fi

cleanup() {
  rc=$?
  if [ -n "$LOG_PID" ]; then
    echo "Stopping log follower pid $LOG_PID"
    kill "$LOG_PID" 2>/dev/null || true
    wait "$LOG_PID" 2>/dev/null || true
  fi
  echo "Artifacts in test-output/"
  # List timestamped per-run artifact directories under test-output
  echo "Artifact run directories (format YYMMDD-HHMMSS):"
  ls -1d test-output/??????-?????? 2>/dev/null || echo "  <none>"
  # Show contents of each run directory (if any)
  for d in test-output/??????-??????; do
    if [ -d "$d" ]; then
      echo "\nContents of $d:";
      ls -la "$d" || true;
    fi
  done
  exit $rc
}

trap cleanup EXIT INT TERM

echo "Running harness (docker compose run --rm -e TEST_MAX_MS=20000 -e TEST_RUN_DIR_NAME=$RUN_DIR_NAME peddlers-test)"
# Run the test harness inside compose; pass TEST_RUN_DIR_NAME so the harness
# writes artifacts into the same per-run directory under /workspace.
docker compose -f docker-compose.yml run --rm -e TEST_MAX_MS=20000 -e TEST_RUN_DIR_NAME=$RUN_DIR_NAME peddlers-test

# Update the latest symlink to point to this run directory so callers can
# quickly find the newest artifacts at test-output/latest
ln -sfn "$LOGDIR" "$OUT_DIR/test-output/latest"
echo "Updated test-output/latest -> $LOGDIR"

echo "Harness completed; cleanup will run via trap"
