#!/usr/bin/env bash
# Auto-generated by epic plugin — runs on SessionStart.
# Installs the epic-harness binary if missing.

set -euo pipefail

# Skip on native Windows (non-WSL) — no cross-compiled binary available
case "$(uname -s 2>/dev/null)" in
  MINGW*|MSYS*|CYGWIN*) exit 0 ;;
esac

PLUGIN_BIN="${CLAUDE_PLUGIN_ROOT:-}/hooks/bin/epic-harness"

# Resolve the binary: plugin-local → PATH
EH=""
if test -x "$PLUGIN_BIN"; then
  EH="$PLUGIN_BIN"
elif command -v epic-harness >/dev/null 2>&1; then
  EH="$(command -v epic-harness)"
fi

# Install if missing
if test -z "$EH"; then
  echo "[epic plugin] epic-harness binary not found — installing..."
  if command -v cargo-binstall >/dev/null 2>&1; then
    cargo binstall -y --no-confirm epic-harness
  elif command -v cargo >/dev/null 2>&1; then
    cargo install epic-harness
  else
    echo "[epic plugin] cargo not found. Install Rust from https://rustup.rs then restart Claude Code." >&2
    exit 0
  fi
  EH="$(command -v epic-harness 2>/dev/null || true)"
fi

# Auto-register MCP server (idempotent — skips if already registered)
if test -n "$EH"; then
  "$EH" mem mcp-install 2>/dev/null || true
fi

# Auto-start knowledge graph web UI (port 7700)
if test -n "$EH"; then
  WEBUI_PORT="${HARNESS_WEBUI_PORT:-7700}"
  if ! [[ "$WEBUI_PORT" =~ ^[0-9]+$ ]] || [ "$WEBUI_PORT" -lt 1 ] || [ "$WEBUI_PORT" -gt 65535 ]; then
    echo "[epic] Invalid HARNESS_WEBUI_PORT value, using default 7700" >&2
    WEBUI_PORT=7700
  fi

  if ! curl -sf "http://127.0.0.1:${WEBUI_PORT}/" >/dev/null 2>&1; then
    # Double-fork to detach from hook process group
    ( "$EH" mem serve --port "$WEBUI_PORT" </dev/null >/dev/null 2>&1 & ) &
    disown 2>/dev/null || true

    # Wait for bind, then open browser
    for _ in 1 2 3; do
      sleep 1
      curl -sf "http://127.0.0.1:${WEBUI_PORT}/" >/dev/null 2>&1 && break
    done
    if curl -sf "http://127.0.0.1:${WEBUI_PORT}/" >/dev/null 2>&1; then
      case "$(uname -s)" in
        Darwin) open "http://localhost:${WEBUI_PORT}" 2>/dev/null ;;
        *)      xdg-open "http://localhost:${WEBUI_PORT}" 2>/dev/null ;;
      esac
    fi
  fi
fi

exit 0
