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

# Wraps any test command and files a Redmine ticket on failure.
# Usage: ./scripts/run-tests-with-redmine.sh <command ...>

if [ "$#" -eq 0 ]; then
  echo "Usage: $0 <command ...>"
  exit 1
fi

RUN_TS=$(date +"%Y%m%d-%H%M%S")
RUN_DIR="reports/runs/manual-${RUN_TS}"
mkdir -p "$RUN_DIR"

CMD=("$@")
NAME="${TEST_NAME:-${CMD[*]}}"
LOG_FILE="$RUN_DIR/command.log"

echo "[run-with-redmine] Running ${CMD[*]}..."
set +e
"${CMD[@]}" >"$LOG_FILE" 2>&1
STATUS=$?
set -e

if [ "$STATUS" -eq 0 ]; then
  echo "[run-with-redmine] Command succeeded. Log: $LOG_FILE"
  exit 0
fi

echo "[run-with-redmine] Command failed with status ${STATUS}. Log: $LOG_FILE"

TAIL_SNIPPET=$(tail -n 40 "$LOG_FILE" 2>/dev/null || true)
FAILURE_FILE="$RUN_DIR/failures.txt"
{
  echo "Command: ${CMD[*]}"
  echo "Exit status: ${STATUS}"
  echo "--- tail ---"
  echo "${TAIL_SNIPPET}"
} >"$FAILURE_FILE"

if command -v node >/dev/null 2>&1 && [ -x "${BASH_SOURCE%/*}/redmine-report.js" ]; then
  if node "${BASH_SOURCE%/*}/redmine-report.js" create-test-issue \
    --suite "${NAME}" \
    --run "$RUN_TS" \
    --fail-count 1 \
    --failures-file "$FAILURE_FILE" \
    --summary-file "$LOG_FILE" \
    --tracker "${TRACKER:-bug}" \
    --fingerprint-seed "${NAME}|${CMD[*]}|${STATUS}|${TAIL_SNIPPET}"; then
    echo "[run-with-redmine] Redmine notification complete."
  else
    echo "[run-with-redmine] Redmine notification failed or skipped."
  fi
else
  echo "[run-with-redmine] Redmine reporter not available; skipping Redmine notification."
fi

exit "$STATUS"
