#!/usr/bin/env bash
# Swap commander's navvi MCP config to use local branch code + branch container image.
# Usage:
#   ./scripts/test-branch-mcp.sh apply   # switch to local dev mode
#   ./scripts/test-branch-mcp.sh revert  # restore uvx production mode

set -euo pipefail

COMMANDER_MCP="/Users/maxfindel/Projects/Fellowship-dev/commander/.mcp.json"
NAVVI_SRC="/Users/maxfindel/Projects/Fellowship-dev/navvi/src"
BRANCH_IMAGE="ghcr.io/fellowship-dev/navvi:fix-atomic-tools-always-visible"

case "${1:-}" in
  apply)
    # Back up original if not already backed up
    if [ ! -f "${COMMANDER_MCP}.bak" ]; then
      cp "$COMMANDER_MCP" "${COMMANDER_MCP}.bak"
      echo "Backed up original to ${COMMANDER_MCP}.bak"
    fi

    cat > "$COMMANDER_MCP" << MCPEOF
{
  "mcpServers": {
    "navvi": {
      "command": "python3",
      "args": ["-c", "from navvi import main; main()"],
      "env": {
        "NAVVI_GPG_PASSPHRASE": "\${NAVVI_GPG_PASSPHRASE}",
        "NAVVI_IMAGE": "${BRANCH_IMAGE}",
        "PYTHONPATH": "${NAVVI_SRC}"
      }
    }
  }
}
MCPEOF

    echo "Applied local dev config:"
    cat "$COMMANDER_MCP"
    echo ""
    echo "Commander will now use:"
    echo "  MCP server: python3 -c 'from navvi import main; main()' (from ${NAVVI_SRC})"
    echo "  Container:  ${BRANCH_IMAGE}"
    echo ""
    echo "Run: ./scripts/test-branch-mcp.sh revert  to restore"
    ;;

  revert)
    if [ -f "${COMMANDER_MCP}.bak" ]; then
      mv "${COMMANDER_MCP}.bak" "$COMMANDER_MCP"
      echo "Reverted to production config:"
      cat "$COMMANDER_MCP"
    else
      echo "No backup found at ${COMMANDER_MCP}.bak — nothing to revert"
      exit 1
    fi
    ;;

  *)
    echo "Usage: $0 {apply|revert}"
    exit 1
    ;;
esac
