#!/usr/bin/env bash
# Standalone uninstaller — reverses install.sh. Logs WhatsApp out, removes the
# bridge OS service, wipes the local store, and unregisters the MCP from Claude
# Code. Safe to run more than once.
#
#   ./uninstall.sh
set -uo pipefail

say() { printf '\033[1;33m[uninstall]\033[0m %s\n' "$*"; }

LABEL="com.whatsapp-mcp.bridge"
case "$(uname -s)" in
  Darwin) APP_DIR="$HOME/Library/Application Support/whatsapp-mcp"
          SERVICE_FILE="$HOME/Library/LaunchAgents/$LABEL.plist" ;;
  *)      APP_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/whatsapp-mcp"
          SERVICE_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/$LABEL.service" ;;
esac

# 1. Log WhatsApp out while the bridge is still alive (unlinks this device).
say "unlinking WhatsApp (logout)…"
curl -s --max-time 5 -X POST http://localhost:8080/api/logout >/dev/null 2>&1 || true

# 2. Remove the OS service.
say "removing the bridge service…"
case "$(uname -s)" in
  Darwin) launchctl bootout "gui/$(id -u)/$LABEL" >/dev/null 2>&1 || true
          rm -f "$SERVICE_FILE" ;;
  *)      systemctl --user disable --now "$LABEL" >/dev/null 2>&1 || true
          rm -f "$SERVICE_FILE"; systemctl --user daemon-reload >/dev/null 2>&1 || true ;;
esac

# 3. Wipe the app dir (binaries + store/credentials).
if [ -d "$APP_DIR" ]; then
  say "removing app data: $APP_DIR"
  rm -rf "$APP_DIR"
fi

# 4. Unregister from Claude Code + remove the skills install.sh added.
if command -v claude >/dev/null 2>&1; then
  claude mcp remove whatsapp >/dev/null 2>&1 && say "unregistered from Claude Code." || true
fi
SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILLS_SRC="$SELF_DIR/skills"
SKILLS_DST="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/skills"
if [ -d "$SKILLS_SRC" ]; then
  for d in "$SKILLS_SRC"/*/; do
    name="$(basename "$d")"
    if [ -d "$SKILLS_DST/$name" ]; then rm -rf "$SKILLS_DST/$name" && say "removed skill: $name"; fi
  done
fi

say "Done. WhatsApp is unlinked and all local data is removed."
