#!/usr/bin/env bash
set -euo pipefail

# MacMD Viewer — AI Coding Tool Integration Setup
# Usage: curl -fsSL https://macmdviewer.com/setup | bash
#        curl -fsSL https://macmdviewer.com/setup | bash -s -- --dry-run
#        curl -fsSL https://macmdviewer.com/setup | bash -s -- --uninstall

VERSION="1.2.0"

# ─── Colors ───────────────────────────────────────────────────────────────────

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
RESET='\033[0m'

# ─── Flags ────────────────────────────────────────────────────────────────────

DRY_RUN=false
UNINSTALL=false

for arg in "$@"; do
  case "$arg" in
    --dry-run)  DRY_RUN=true ;;
    --uninstall) UNINSTALL=true ;;
    --version)  echo "MacMD Viewer setup v${VERSION}"; exit 0 ;;
    --help|-h)
      echo "MacMD Viewer — AI Coding Tool Integration Setup"
      echo ""
      echo "Usage:"
      echo "  curl -fsSL https://macmdviewer.com/setup | bash"
      echo "  curl -fsSL https://macmdviewer.com/setup | bash -s -- --dry-run"
      echo "  curl -fsSL https://macmdviewer.com/setup | bash -s -- --uninstall"
      echo ""
      echo "Flags:"
      echo "  --dry-run     Show what would change without modifying anything"
      echo "  --uninstall   Remove MacMD Viewer hooks from all configured tools"
      echo "  --version     Print version"
      echo "  --help        Show this help"
      exit 0
      ;;
    *)
      echo -e "${RED}Unknown option: ${arg}${RESET}"
      echo "Run with --help for usage."
      exit 1
      ;;
  esac
done

# ─── Helpers ──────────────────────────────────────────────────────────────────

info()    { echo -e "${BLUE}ℹ${RESET}  $1"; }
success() { echo -e "${GREEN}✓${RESET}  $1"; }
warn()    { echo -e "${YELLOW}!${RESET}  $1"; }
err()     { echo -e "${RED}✗${RESET}  $1"; }
step()    { echo -e "${CYAN}▸${RESET}  $1"; }

HOOK_MARKER="MacMD Viewer"
CHANGES_MADE=0
TOOLS_DETECTED=0
TOOLS_CONFIGURED=0

# Determine JSON editing strategy
JSON_TOOL="none"
if command -v jq &>/dev/null; then
  JSON_TOOL="jq"
elif command -v python3 &>/dev/null; then
  JSON_TOOL="python3"
elif command -v python &>/dev/null; then
  JSON_TOOL="python"
fi

backup_file() {
  local file="$1"
  if [[ -f "$file" ]]; then
    local timestamp
    timestamp=$(date +%Y%m%d_%H%M%S)
    local backup="${file}.bak.${timestamp}"
    cp "$file" "$backup"
    info "Backed up ${DIM}${file}${RESET} → ${DIM}${backup}${RESET}"
  fi
}

ask_yes_no() {
  local prompt="$1"
  local default="${2:-Y}"

  if [[ "$default" == "Y" ]]; then
    prompt="${prompt} [Y/n] "
  else
    prompt="${prompt} [y/N] "
  fi

  # If stdin is not a terminal (piped), default to yes
  if [[ ! -t 0 ]]; then
    return 0
  fi

  read -r -p "$(echo -e "${BOLD}?${RESET}  ${prompt}")" answer </dev/tty
  case "${answer:-$default}" in
    [Yy]*) return 0 ;;
    *)     return 1 ;;
  esac
}

file_contains_marker() {
  local file="$1"
  grep -q "$HOOK_MARKER" "$file" 2>/dev/null
}

# ─── JSON Manipulation ───────────────────────────────────────────────────────

# Merges a hook into a JSON config file using jq or python.
# $1 = file path
# $2 = jq filter expression
# $3 = python script
# Returns 0 on success, 1 on failure (caller should print manual instructions)
json_merge() {
  local file="$1"
  local jq_filter="$2"
  local python_script="$3"

  if [[ "$JSON_TOOL" == "jq" ]]; then
    local tmp
    tmp=$(mktemp)
    if jq "$jq_filter" "$file" > "$tmp" 2>/dev/null; then
      mv "$tmp" "$file"
      return 0
    else
      rm -f "$tmp"
      return 1
    fi
  elif [[ "$JSON_TOOL" == "python3" || "$JSON_TOOL" == "python" ]]; then
    local tmp
    tmp=$(mktemp)
    if $JSON_TOOL -c "$python_script" "$file" > "$tmp" 2>/dev/null; then
      mv "$tmp" "$file"
      return 0
    else
      rm -f "$tmp"
      return 1
    fi
  else
    return 1
  fi
}

# Removes MacMD Viewer hooks from a JSON file.
# $1 = file path
# $2 = jq filter for removal
# $3 = python script for removal
json_remove() {
  json_merge "$1" "$2" "$3"
}

# ─── Claude Code ──────────────────────────────────────────────────────────────

CLAUDE_CONFIG="$HOME/.claude/settings.json"
CLAUDE_SENTINEL="$HOME/.claude/.macmd-autoopen"
CLAUDE_SKILL_DIR="$HOME/.claude/skills/macmd"

detect_claude() {
  [[ -f "$CLAUDE_CONFIG" ]]
}

claude_already_configured() {
  file_contains_marker "$CLAUDE_CONFIG"
}

# Write the /macmd skill: open a file on demand + toggle auto-open on/off.
write_macmd_skill() {
  mkdir -p "$CLAUDE_SKILL_DIR"
  cat > "$CLAUDE_SKILL_DIR/SKILL.md" <<'SKILLEOF'
---
name: macmd
description: Open a Markdown file in MacMD Viewer, or toggle auto-open of new .md files. Use when the user types /macmd, asks to open or preview a markdown file in MacMD Viewer, or wants to turn auto-open on or off.
---

# /macmd — open Markdown in MacMD Viewer

Installed app bundle id: `com.arthur.MarkdownViewer`. Open a file (foreground,
window in front) with:

    open -b com.arthur.MarkdownViewer "<absolute-path>"

If that command reports the application can't be found, MacMD Viewer is not
installed — tell the user and point them to https://macmdviewer.com.

Auto-open of newly written or edited `.md` files is a separate `PostToolUse` hook
in `~/.claude/settings.json`, gated by the sentinel file
`~/.claude/.macmd-autoopen` (absent = OFF). This skill is the manual path and the
on/off toggle.

## Dispatch on the argument

- **No argument** → open the most recent `.md` you created or edited in this
  conversation (you know which from context). If none is obvious, ask which file.
  Always pass an absolute path.
- **A path** (e.g. `/macmd docs/plan.md`) → resolve it against the current working
  directory if relative, then open it.
- **`on`** → run `touch ~/.claude/.macmd-autoopen`, then confirm auto-open is on.
- **`off`** → run `rm -f ~/.claude/.macmd-autoopen`, then confirm auto-open is off.
- **`status`** → report whether `~/.claude/.macmd-autoopen` exists (ON / OFF).

Do not pass `-g` when opening here: a manual `/macmd` should bring the window to
the front.
SKILLEOF
}

install_claude() {
  local hook_present=false
  if claude_already_configured; then hook_present=true; fi

  if $DRY_RUN; then
    if $hook_present; then
      info "Claude Code — auto-open hook already present"
    else
      info "Would add a sentinel-gated PostToolUse hook to ${DIM}${CLAUDE_CONFIG}${RESET}"
    fi
    info "Would install the ${BOLD}/macmd${RESET} skill to ${DIM}${CLAUDE_SKILL_DIR}${RESET} and enable auto-open"
    return 0
  fi

  if ! $hook_present; then
    backup_file "$CLAUDE_CONFIG"

    local jq_filter
    jq_filter=$(cat <<'JQEOF'
# Ensure .hooks.PostToolUse exists as an array, then append our entry
.hooks //= {} |
.hooks.PostToolUse //= [] |
.hooks.PostToolUse += [{
  "matcher": "Write|Edit",
  "hooks": [{
    "type": "command",
    "command": "[ -f \"$HOME/.claude/.macmd-autoopen\" ] || exit 0; case \"$TOOL_INPUT_file_path\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$TOOL_INPUT_file_path\" 2>/dev/null ;; esac"
  }]
}]
JQEOF
)

    local python_script
    python_script=$(cat <<'PYEOF'
import json, sys
with open(sys.argv[1], 'r') as f:
    data = json.load(f)
data.setdefault('hooks', {})
data['hooks'].setdefault('PostToolUse', [])
new_hook = {
    "matcher": "Write|Edit",
    "hooks": [{
        "type": "command",
        "command": "[ -f \"$HOME/.claude/.macmd-autoopen\" ] || exit 0; case \"$TOOL_INPUT_file_path\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$TOOL_INPUT_file_path\" 2>/dev/null ;; esac"
    }]
}
data['hooks']['PostToolUse'].append(new_hook)
print(json.dumps(data, indent=2))
PYEOF
)

    if json_merge "$CLAUDE_CONFIG" "$jq_filter" "$python_script"; then
      success "Claude Code — auto-open hook installed"
    else
      warn "Claude Code — could not auto-edit config. Add this manually to ${CLAUDE_CONFIG}:"
      echo ""
      cat <<'MANUAL'
  In "hooks" > "PostToolUse", add:
  {
    "matcher": "Write|Edit",
    "hooks": [{
      "type": "command",
      "command": "[ -f \"$HOME/.claude/.macmd-autoopen\" ] || exit 0; case \"$TOOL_INPUT_file_path\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$TOOL_INPUT_file_path\" 2>/dev/null ;; esac"
    }]
  }
MANUAL
      echo ""
    fi
  else
    success "Claude Code — auto-open hook already present"
  fi

  write_macmd_skill
  touch "$CLAUDE_SENTINEL"
  success "Claude Code — ${BOLD}/macmd${RESET} skill installed; auto-open ${GREEN}ON${RESET} ${DIM}(toggle: /macmd on|off)${RESET}"
  ((CHANGES_MADE++)) || true
}

uninstall_claude() {
  local found=false
  if claude_already_configured; then found=true; fi
  if [[ -e "$CLAUDE_SKILL_DIR" ]]; then found=true; fi
  if [[ -e "$CLAUDE_SENTINEL" ]]; then found=true; fi

  if ! $found; then
    info "Claude Code — no MacMD Viewer integration found, nothing to remove"
    return 0
  fi

  if $DRY_RUN; then
    info "Would remove the hook, ${BOLD}/macmd${RESET} skill, and sentinel from ${DIM}~/.claude${RESET}"
    return 0
  fi

  if claude_already_configured; then
    backup_file "$CLAUDE_CONFIG"

    local jq_filter
    jq_filter=$(cat <<'JQEOF'
if .hooks.PostToolUse then
  .hooks.PostToolUse |= map(select(.hooks | tostring | contains("MacMD Viewer") | not))
else . end |
if .hooks.PostToolUse == [] then del(.hooks.PostToolUse) else . end
JQEOF
)

    local python_script
    python_script=$(cat <<'PYEOF'
import json, sys
with open(sys.argv[1], 'r') as f:
    data = json.load(f)
if 'hooks' in data and 'PostToolUse' in data['hooks']:
    data['hooks']['PostToolUse'] = [
        h for h in data['hooks']['PostToolUse']
        if 'MacMD Viewer' not in json.dumps(h)
    ]
    if not data['hooks']['PostToolUse']:
        del data['hooks']['PostToolUse']
print(json.dumps(data, indent=2))
PYEOF
)

    if json_remove "$CLAUDE_CONFIG" "$jq_filter" "$python_script"; then
      success "Claude Code — hook removed"
    else
      warn "Claude Code — could not auto-remove the hook. Please edit ${CLAUDE_CONFIG} manually."
    fi
  fi

  if [[ -e "$CLAUDE_SKILL_DIR" ]]; then
    rm -rf "$CLAUDE_SKILL_DIR"
    success "Claude Code — /macmd skill removed"
  fi
  rm -f "$CLAUDE_SENTINEL"
  ((CHANGES_MADE++)) || true
}

# ─── Cursor ──────────────────────────────────────────────────────────────────

CURSOR_DIR="$HOME/.cursor"
CURSOR_CONFIG="$CURSOR_DIR/hooks.json"

detect_cursor() {
  [[ -d "$CURSOR_DIR" ]]
}

cursor_already_configured() {
  [[ -f "$CURSOR_CONFIG" ]] && file_contains_marker "$CURSOR_CONFIG"
}

install_cursor() {
  if cursor_already_configured; then
    success "Cursor — already configured, skipping"
    return 0
  fi

  if $DRY_RUN; then
    info "Would add afterFileEdit hook to ${DIM}${CURSOR_CONFIG}${RESET}"
    return 0
  fi

  # If hooks.json doesn't exist, create it from scratch
  if [[ ! -f "$CURSOR_CONFIG" ]]; then
    cat > "$CURSOR_CONFIG" <<'HOOKJSON'
{
  "version": 1,
  "hooks": {
    "afterFileEdit": [
      {
        "command": "case \"$FILE_PATH\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$FILE_PATH\" 2>/dev/null ;; esac"
      }
    ]
  }
}
HOOKJSON
    success "Cursor — hook installed (created ${DIM}${CURSOR_CONFIG}${RESET})"
    ((CHANGES_MADE++)) || true
    return 0
  fi

  backup_file "$CURSOR_CONFIG"

  local jq_filter
  jq_filter=$(cat <<'JQEOF'
.hooks //= {} |
.hooks.afterFileEdit //= [] |
.hooks.afterFileEdit += [{
  "command": "case \"$FILE_PATH\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$FILE_PATH\" 2>/dev/null ;; esac"
}]
JQEOF
)

  local python_script
  python_script=$(cat <<'PYEOF'
import json, sys
with open(sys.argv[1], 'r') as f:
    data = json.load(f)
data.setdefault('hooks', {})
data['hooks'].setdefault('afterFileEdit', [])
new_hook = {
    "command": "case \"$FILE_PATH\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$FILE_PATH\" 2>/dev/null ;; esac"
}
data['hooks']['afterFileEdit'].append(new_hook)
if 'version' not in data:
    data['version'] = 1
print(json.dumps(data, indent=2))
PYEOF
)

  if json_merge "$CURSOR_CONFIG" "$jq_filter" "$python_script"; then
    success "Cursor — hook installed"
    ((CHANGES_MADE++)) || true
  else
    warn "Cursor — could not auto-edit config. Add this to ${CURSOR_CONFIG}:"
    echo ""
    cat <<'MANUAL'
  In "hooks" > "afterFileEdit", add:
  {
    "command": "case \"$FILE_PATH\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$FILE_PATH\" 2>/dev/null ;; esac"
  }
MANUAL
    echo ""
  fi
}

uninstall_cursor() {
  if ! cursor_already_configured; then
    info "Cursor — no MacMD Viewer hook found, nothing to remove"
    return 0
  fi

  if $DRY_RUN; then
    info "Would remove afterFileEdit hook from ${DIM}${CURSOR_CONFIG}${RESET}"
    return 0
  fi

  backup_file "$CURSOR_CONFIG"

  local jq_filter
  jq_filter=$(cat <<'JQEOF'
if .hooks.afterFileEdit then
  .hooks.afterFileEdit |= map(select(.command | tostring | contains("MacMD Viewer") | not))
else . end |
if .hooks.afterFileEdit == [] then del(.hooks.afterFileEdit) else . end
JQEOF
)

  local python_script
  python_script=$(cat <<'PYEOF'
import json, sys
with open(sys.argv[1], 'r') as f:
    data = json.load(f)
if 'hooks' in data and 'afterFileEdit' in data['hooks']:
    data['hooks']['afterFileEdit'] = [
        h for h in data['hooks']['afterFileEdit']
        if 'MacMD Viewer' not in json.dumps(h)
    ]
    if not data['hooks']['afterFileEdit']:
        del data['hooks']['afterFileEdit']
print(json.dumps(data, indent=2))
PYEOF
)

  if json_remove "$CURSOR_CONFIG" "$jq_filter" "$python_script"; then
    success "Cursor — hook removed"
    ((CHANGES_MADE++)) || true
  else
    warn "Cursor — could not auto-remove. Please edit ${CURSOR_CONFIG} manually."
  fi
}

# ─── VS Code / GitHub Copilot ────────────────────────────────────────────────

VSCODE_DIR="$HOME/.vscode"
VSCODE_SETTINGS="$HOME/Library/Application Support/Code/User/settings.json"

detect_vscode() {
  [[ -d "$VSCODE_DIR" ]] || [[ -d "$HOME/Library/Application Support/Code" ]]
}

vscode_already_configured() {
  [[ -f "$VSCODE_SETTINGS" ]] && file_contains_marker "$VSCODE_SETTINGS"
}

install_vscode() {
  if vscode_already_configured; then
    success "VS Code — already configured, skipping"
    return 0
  fi

  # VS Code doesn't have a native file-edit hook system like Claude/Cursor.
  # The best approach is the "Run on Save" extension.
  if $DRY_RUN; then
    info "Would print VS Code setup instructions"
    return 0
  fi

  echo ""
  info "VS Code / GitHub Copilot — manual setup required:"
  echo ""
  echo -e "  ${BOLD}1.${RESET} Install the ${CYAN}Run on Save${RESET} extension (emeraldwalk.runonsave)"
  echo -e "  ${BOLD}2.${RESET} Add to your settings.json (${DIM}Cmd+Shift+P → Preferences: Open User Settings (JSON)${RESET}):"
  echo ""
  echo -e "  ${DIM}\"emeraldwalk.runonsave\": {"
  echo -e "    \"commands\": ["
  echo -e "      {"
  echo -e "        \"match\": \"\\\\.md$\","
  echo -e "        \"cmd\": \"open -g -a 'MacMD Viewer' '\\\${file}'\""
  echo -e "      }"
  echo -e "    ]"
  echo -e "  }${RESET}"
  echo ""
}

uninstall_vscode() {
  if ! vscode_already_configured; then
    info "VS Code — no MacMD Viewer config found"
    return 0
  fi
  echo ""
  info "VS Code — please manually remove the MacMD Viewer entry from:"
  echo -e "  ${DIM}${VSCODE_SETTINGS}${RESET}"
  echo ""
}

# ─── Windsurf ────────────────────────────────────────────────────────────────

WINDSURF_DIR="$HOME/Library/Application Support/Windsurf"
WINDSURF_CONFIG="$WINDSURF_DIR/hooks.json"

detect_windsurf() {
  [[ -d "$WINDSURF_DIR" ]]
}

windsurf_already_configured() {
  [[ -f "$WINDSURF_CONFIG" ]] && file_contains_marker "$WINDSURF_CONFIG"
}

install_windsurf() {
  if windsurf_already_configured; then
    success "Windsurf — already configured, skipping"
    return 0
  fi

  if $DRY_RUN; then
    info "Would add post_cascade_response hook to ${DIM}${WINDSURF_CONFIG}${RESET}"
    return 0
  fi

  if [[ ! -f "$WINDSURF_CONFIG" ]]; then
    cat > "$WINDSURF_CONFIG" <<'HOOKJSON'
{
  "hooks": {
    "post_cascade_response": [
      {
        "command": "case \"$FILE_PATH\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$FILE_PATH\" 2>/dev/null ;; esac"
      }
    ]
  }
}
HOOKJSON
    success "Windsurf — hook installed (created ${DIM}${WINDSURF_CONFIG}${RESET})"
    ((CHANGES_MADE++)) || true
    return 0
  fi

  backup_file "$WINDSURF_CONFIG"

  local jq_filter
  jq_filter=$(cat <<'JQEOF'
.hooks //= {} |
.hooks.post_cascade_response //= [] |
.hooks.post_cascade_response += [{
  "command": "case \"$FILE_PATH\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$FILE_PATH\" 2>/dev/null ;; esac"
}]
JQEOF
)

  local python_script
  python_script=$(cat <<'PYEOF'
import json, sys
with open(sys.argv[1], 'r') as f:
    data = json.load(f)
data.setdefault('hooks', {})
data['hooks'].setdefault('post_cascade_response', [])
new_hook = {
    "command": "case \"$FILE_PATH\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$FILE_PATH\" 2>/dev/null ;; esac"
}
data['hooks']['post_cascade_response'].append(new_hook)
print(json.dumps(data, indent=2))
PYEOF
)

  if json_merge "$WINDSURF_CONFIG" "$jq_filter" "$python_script"; then
    success "Windsurf — hook installed"
    ((CHANGES_MADE++)) || true
  else
    warn "Windsurf — could not auto-edit config. Add this to ${WINDSURF_CONFIG}:"
    echo ""
    cat <<'MANUAL'
  In "hooks" > "post_cascade_response", add:
  {
    "command": "case \"$FILE_PATH\" in memory/*|*/memory/*|node_modules/*|*/node_modules/*|.build/*|*/.build/*|DerivedData/*|*/DerivedData/*|.next/*|*/.next/*|dist/*|*/dist/*|/tmp/*|/private/tmp/*|/private/var/folders/*) ;; *.md|*.markdown) open -g -a 'MacMD Viewer' \"$FILE_PATH\" 2>/dev/null ;; esac"
  }
MANUAL
    echo ""
  fi
}

uninstall_windsurf() {
  if ! windsurf_already_configured; then
    info "Windsurf — no MacMD Viewer hook found, nothing to remove"
    return 0
  fi

  if $DRY_RUN; then
    info "Would remove post_cascade_response hook from ${DIM}${WINDSURF_CONFIG}${RESET}"
    return 0
  fi

  backup_file "$WINDSURF_CONFIG"

  local jq_filter
  jq_filter=$(cat <<'JQEOF'
if .hooks.post_cascade_response then
  .hooks.post_cascade_response |= map(select(.command | tostring | contains("MacMD Viewer") | not))
else . end |
if .hooks.post_cascade_response == [] then del(.hooks.post_cascade_response) else . end
JQEOF
)

  local python_script
  python_script=$(cat <<'PYEOF'
import json, sys
with open(sys.argv[1], 'r') as f:
    data = json.load(f)
if 'hooks' in data and 'post_cascade_response' in data['hooks']:
    data['hooks']['post_cascade_response'] = [
        h for h in data['hooks']['post_cascade_response']
        if 'MacMD Viewer' not in json.dumps(h)
    ]
    if not data['hooks']['post_cascade_response']:
        del data['hooks']['post_cascade_response']
print(json.dumps(data, indent=2))
PYEOF
)

  if json_remove "$WINDSURF_CONFIG" "$jq_filter" "$python_script"; then
    success "Windsurf — hook removed"
    ((CHANGES_MADE++)) || true
  else
    warn "Windsurf — could not auto-remove. Please edit ${WINDSURF_CONFIG} manually."
  fi
}

# ─── JetBrains ───────────────────────────────────────────────────────────────

JETBRAINS_DIR="$HOME/Library/Application Support/JetBrains"

detect_jetbrains() {
  [[ -d "$JETBRAINS_DIR" ]]
}

install_jetbrains() {
  if $DRY_RUN; then
    info "Would print JetBrains setup instructions"
    return 0
  fi

  echo ""
  info "JetBrains IDE — manual setup required:"
  echo ""
  echo -e "  ${BOLD}1.${RESET} Install the ${CYAN}File Watchers${RESET} plugin (Settings → Plugins)"
  echo -e "  ${BOLD}2.${RESET} Go to Settings → Tools → File Watchers → ${BOLD}+${RESET}"
  echo -e "  ${BOLD}3.${RESET} Configure:"
  echo -e "     File type:    ${DIM}Markdown${RESET}"
  echo -e "     Scope:        ${DIM}All Places${RESET}"
  echo -e "     Program:      ${DIM}open${RESET}"
  echo -e "     Arguments:    ${DIM}-g -a \"MacMD Viewer\" \"\$FilePath\$\"${RESET}"
  echo -e "     Trigger:      ${DIM}On save / On change${RESET}"
  echo ""
}

uninstall_jetbrains() {
  echo ""
  info "JetBrains — please manually remove the MacMD Viewer File Watcher:"
  echo -e "  Settings → Tools → File Watchers → select MacMD Viewer → ${BOLD}-${RESET}"
  echo ""
}

# ─── Aider ───────────────────────────────────────────────────────────────────

AIDER_CONFIG="$HOME/.aider.conf.yml"

detect_aider() {
  [[ -f "$AIDER_CONFIG" ]] || command -v aider &>/dev/null
}

# ─── Banner ──────────────────────────────────────────────────────────────────

print_banner() {
  echo ""
  echo -e "${BOLD}  MacMD Viewer${RESET} — AI Coding Tool Integration Setup ${DIM}v${VERSION}${RESET}"
  echo -e "  ${DIM}Auto-preview Markdown files as your AI edits them${RESET}"
  echo ""

  if $DRY_RUN; then
    echo -e "  ${YELLOW}DRY RUN — no files will be modified${RESET}"
    echo ""
  fi

  if $UNINSTALL; then
    echo -e "  ${YELLOW}UNINSTALL MODE — removing MacMD Viewer hooks${RESET}"
    echo ""
  fi
}

# ─── Detection Phase ────────────────────────────────────────────────────────

declare -a DETECTED_TOOLS=()

detect_all() {
  echo -e "${BOLD}  Scanning for AI coding tools...${RESET}"
  echo ""

  if detect_claude; then
    success "Claude Code detected ${DIM}(${CLAUDE_CONFIG})${RESET}"
    DETECTED_TOOLS+=("claude")
    ((TOOLS_DETECTED++)) || true
  fi

  if detect_cursor; then
    success "Cursor detected ${DIM}(${CURSOR_DIR})${RESET}"
    DETECTED_TOOLS+=("cursor")
    ((TOOLS_DETECTED++)) || true
  fi

  if detect_vscode; then
    success "VS Code detected"
    DETECTED_TOOLS+=("vscode")
    ((TOOLS_DETECTED++)) || true
  fi

  if detect_windsurf; then
    success "Windsurf detected ${DIM}(${WINDSURF_DIR})${RESET}"
    DETECTED_TOOLS+=("windsurf")
    ((TOOLS_DETECTED++)) || true
  fi

  if detect_jetbrains; then
    success "JetBrains IDE detected ${DIM}(${JETBRAINS_DIR})${RESET}"
    DETECTED_TOOLS+=("jetbrains")
    ((TOOLS_DETECTED++)) || true
  fi

  if detect_aider; then
    success "Aider detected ${DIM}(skipped — no native hook support)${RESET}"
    # Don't add to DETECTED_TOOLS; we skip aider
  fi

  echo ""

  if [[ ${#DETECTED_TOOLS[@]} -eq 0 ]]; then
    warn "No supported AI coding tools detected."
    echo ""
    echo -e "  Supported tools: Claude Code, Cursor, VS Code, Windsurf, JetBrains"
    echo -e "  Make sure they are installed before running this script."
    echo ""
    exit 0
  fi

  info "Found ${BOLD}${TOOLS_DETECTED}${RESET} tool(s) to configure"
  echo ""
}

# ─── Install / Uninstall Phase ───────────────────────────────────────────────

get_display_name() {
  case "$1" in
    claude)    echo "Claude Code" ;;
    cursor)    echo "Cursor" ;;
    vscode)    echo "VS Code / GitHub Copilot" ;;
    windsurf)  echo "Windsurf" ;;
    jetbrains) echo "JetBrains IDE" ;;
    *)         echo "$1" ;;
  esac
}

process_tools() {
  for tool in "${DETECTED_TOOLS[@]}"; do
    local display_name
    display_name="$(get_display_name "$tool")"

    if $UNINSTALL; then
      step "Removing from ${BOLD}${display_name}${RESET}..."
      "uninstall_${tool}"
    else
      if ask_yes_no "Configure auto-preview for ${BOLD}${display_name}${RESET}?"; then
        step "Configuring ${BOLD}${display_name}${RESET}..."
        "install_${tool}"
        ((TOOLS_CONFIGURED++)) || true
      else
        info "Skipped ${display_name}"
      fi
    fi
  done
}

# ─── Summary ─────────────────────────────────────────────────────────────────

print_summary() {
  echo ""
  echo -e "  ${BOLD}─────────────────────────────────${RESET}"
  echo ""

  if $DRY_RUN; then
    info "Dry run complete. No files were modified."
  elif $UNINSTALL; then
    if [[ $CHANGES_MADE -gt 0 ]]; then
      success "Uninstalled MacMD Viewer hooks from ${CHANGES_MADE} tool(s)"
    else
      info "Nothing to remove"
    fi
  else
    if [[ $CHANGES_MADE -gt 0 ]]; then
      echo -e "  ${GREEN}${BOLD}Done!${RESET} Configured ${CHANGES_MADE} tool(s)."
      echo ""
      echo -e "  ${DIM}Now when your AI edits a .md file, MacMD Viewer will open it automatically.${RESET}"
      echo -e "  ${DIM}Claude Code: type ${RESET}${BOLD}/macmd${RESET}${DIM} to open the latest file, or ${RESET}${BOLD}/macmd off${RESET}${DIM} to pause auto-open.${RESET}"
    elif [[ $TOOLS_CONFIGURED -gt 0 ]]; then
      echo -e "  ${GREEN}${BOLD}Done!${RESET} See the manual instructions above."
    else
      info "No changes made."
    fi
  fi

  echo ""
  echo -e "  ${DIM}Docs: https://macmdviewer.com/docs/integrations${RESET}"
  echo -e "  ${DIM}Undo: curl -fsSL https://macmdviewer.com/setup | bash -s -- --uninstall${RESET}"
  echo ""
}

# ─── Main ────────────────────────────────────────────────────────────────────

main() {
  print_banner
  detect_all
  process_tools
  print_summary
}

main
