#!/bin/bash
# Example: run_test hook
#
# This hook runs tests and reports the status back to dmux via the HTTP API.
# Status updates appear in real-time in the dmux UI.

set -e

echo "[Hook] Running tests for $DMUX_SLUG"

cd "$DMUX_WORKTREE_PATH"
API_URL="http://localhost:$DMUX_SERVER_PORT/api/panes/$DMUX_PANE_ID/test"

# Update status: running
curl -s -X PUT "$API_URL" \
  -H "Content-Type: application/json" \
  -d '{"status": "running"}' > /dev/null

echo "[Hook] Running test suite..."

# Capture test output
OUTPUT_FILE="/tmp/dmux-test-$DMUX_PANE_ID.txt"

# Run tests (adjust command for your project)
# Examples:
#   - pnpm test
#   - npm test
#   - vitest run
#   - jest
#   - pytest
#   - cargo test
if pnpm test > "$OUTPUT_FILE" 2>&1; then
  STATUS="passed"
  echo "[Hook] Tests passed ✓"
else
  STATUS="failed"
  echo "[Hook] Tests failed ✗"
fi

# Get output (truncate if too long)
OUTPUT=$(head -c 5000 "$OUTPUT_FILE")

# Report results back to dmux
curl -s -X PUT "$API_URL" \
  -H "Content-Type: application/json" \
  -d "$(jq -n \
    --arg status "$STATUS" \
    --arg output "$OUTPUT" \
    '{status: $status, output: $output}')" > /dev/null

# Cleanup
rm -f "$OUTPUT_FILE"

echo "[Hook] Test results reported to dmux"

# Exit with test status
if [ "$STATUS" = "passed" ]; then
  exit 0
else
  exit 1
fi
