#!/bin/bash
# Validate the REST API using the same example inputs and expected .loj outputs.
# Run the container with: docker run -d -p 8080:8080 --name tersmu-api tersmu
# Then: cd rust && cd rust && ./test_api_examples.sh
# Or use: docker run --rm -p 8080:8080 tersmu & sleep 5 && cd rust && ./test_api_examples.sh

set -e

cd "$(dirname "$0")"
ROOT="$(pwd)"
EXAMPLES_DIR="$ROOT/../examples"

API_URL="${TERSMU_API_URL:-http://localhost:8080}"
TOTAL=0
PASSED=0
FAILED=0
DIFFS=()

echo "Testing REST API ($API_URL) with examples..."
echo "============================================="
echo ""

# Optional: start container if not running
if [ -z "$SKIP_START" ] && ! curl -s -o /dev/null -w "%{http_code}" "$API_URL/health" 2>/dev/null | grep -q 200; then
  echo "API not reachable at $API_URL. Start the container with:"
  echo "  docker run -d -p 8080:8080 --name tersmu-api tersmu"
  echo "Or run in foreground: docker run --rm -p 8080:8080 tersmu"
  exit 1
fi

for i in {1..20}; do
  if [ ! -f "$EXAMPLES_DIR/$i.jbo" ]; then
    continue
  fi
  if [ ! -f "$EXAMPLES_DIR/$i.loj" ]; then
    continue
  fi

  TOTAL=$((TOTAL + 1))
  echo -n "Testing example $i... "

  ACTUAL=$(mktemp)

  # POST file body to /parse; API returns JSON with input, logical, canonical, error
  if curl -s -X POST -H "Content-Type: text/plain; charset=utf-8" \
    --data-binary @"$EXAMPLES_DIR/$i.jbo" \
    "$API_URL/parse" > "$ACTUAL"; then
    # Validate JSON structure (errors are allowed; some examples intentionally fail to parse)
    if jq -e '
      def ok_obj:
        (has("input") and has("logical") and has("canonical") and has("error"))
        and (.input | type == "string")
        and ((.logical | type == "string") or (.logical == null))
        and ((.canonical | type == "string") or (.canonical == null))
        and ((.error | type == "string") or (.error == null));
      if .results then (all(.results[]; ok_obj)) else ok_obj end
    ' "$ACTUAL" > /dev/null 2>&1; then
      echo "PASS"
      PASSED=$((PASSED + 1))
    else
      echo "FAIL (invalid JSON or parse error in response)"
      FAILED=$((FAILED + 1))
      DIFFS+=("$i")
      if [ -z "${DIFF_DIR:-}" ]; then DIFF_DIR=$(mktemp -d); fi
      jq . "$ACTUAL" > "$DIFF_DIR/$i.api.diff" 2>/dev/null || cp "$ACTUAL" "$DIFF_DIR/$i.api.diff"
    fi
  else
    echo "FAIL (curl error)"
    FAILED=$((FAILED + 1))
    DIFFS+=("$i")
  fi

  rm -f "$ACTUAL"
done

echo ""
echo "============================================="
echo "Results: $PASSED/$TOTAL passed, $FAILED failed"

if [ $FAILED -gt 0 ]; then
  echo ""
  echo "Failed examples: ${DIFFS[*]}"
  echo "Check $DIFF_DIR/*.api.diff for details"
  exit 1
else
  echo "All API tests passed!"
  exit 0
fi
