#!/bin/bash
# patch-copilot-sdk.sh — bash 3.2+ compatible (macOS/Linux)
set -uo pipefail
# Note: no -e, we handle errors manually to avoid silent exits on find/grep

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

info()    { printf "${CYAN}[INFO]${RESET}  %s\n" "$*"; }
success() { printf "${GREEN}[OK]${RESET}    %s\n" "$*"; }
warn()    { printf "${YELLOW}[WARN]${RESET}  %s\n" "$*"; }
error()   { printf "${RED}[ERROR]${RESET} %s\n" "$*" >&2; }
die()     { error "$*"; exit 1; }

printf "\n${BOLD}╔══════════════════════════════════════════════════╗\n"
printf "║   GitHub Copilot SDK Patcher — v0.45.1          ║\n"
printf "╚══════════════════════════════════════════════════╝${RESET}\n\n"

# ── 1. Check perl ────────────────────────────────────────────
command -v perl >/dev/null 2>&1 || die "perl not found in PATH."
success "perl found: $(command -v perl)"

# ── 2. Locate target file ────────────────────────────────────
RELATIVE_PATH="node_modules/@github/copilot/sdk/index.js"

CANDIDATE_DIRS=(
  "$HOME/.vscode/extensions"
  "$HOME/.vscode-server/extensions"
  "$HOME/.vscode-insiders/extensions"
  "$HOME/.cursor/extensions"
)
if [ "$(uname)" = "Darwin" ]; then
  CANDIDATE_DIRS=(
    "${CANDIDATE_DIRS[@]}"
    "$HOME/Library/Application Support/Code/extensions"
    "$HOME/Library/Application Support/Cursor/User/extensions"
  )
fi

TARGET=""

if [ $# -ge 1 ]; then
  TARGET="$1"
  [ -f "$TARGET" ] || die "Specified file not found: $TARGET"
  info "Using explicit path: $TARGET"
else
  info "Searching for Copilot SDK index.js ..."

  # Simple loop — no find, no subshell, no pipefail trap
  for dir in "${CANDIDATE_DIRS[@]}"; do
    [ -d "$dir" ] || continue
    # Glob over all github.copilot-chat-* subdirs
    for extdir in "$dir"/github.copilot-chat-*; do
      [ -d "$extdir" ] || continue
      candidate="$extdir/$RELATIVE_PATH"
      if [ -f "$candidate" ]; then
        info "Found: $candidate"
        if [ -z "$TARGET" ]; then
          TARGET="$candidate"
        else
          warn "Also found: $candidate (ignored, using first match)"
        fi
      fi
    done
  done

  if [ -z "$TARGET" ]; then
    printf "\n"
    error "Could not find the Copilot SDK index.js automatically."
    printf "  Searched in:\n"
    for d in "${CANDIDATE_DIRS[@]}"; do printf "    %s\n" "$d"; done
    printf "\n  Run manually:\n"
    printf "    bash %s /path/to/index.js\n\n" "$0"
    exit 1
  fi
fi

success "Target: $TARGET"

# ── 3. Already patched? ──────────────────────────────────────
SENTINEL='includeCoAuthoredBy'
if grep -qF "$SENTINEL" "$TARGET" 2>/dev/null; then
  warn "Patch already applied. Nothing to do."
  exit 0
fi

# ── 4. Backup ────────────────────────────────────────────────
BACKUP="${TARGET}.bak.$(date +%Y%m%d_%H%M%S)"
cp "$TARGET" "$BACKUP" || die "Could not create backup."
success "Backup saved: $BACKUP"

# ── 5. Apply patch ───────────────────────────────────────────
info "Applying patch..."

perl -pi -e \
  's/if\(!vr\(e,lXe\)\{/if(!vr(e,lXe) \&\& e.includeCoAuthoredBy!==false){/g;
   s/if\(!n&&r\.cwd&&vr\(e,lXe\)\)\{/if(!n\&\&r.cwd\&\&vr(e,lXe) \&\& e.includeCoAuthoredBy!==false){/g' \
  "$TARGET" || { cp "$BACKUP" "$TARGET"; die "perl failed — rolled back."; }

# ── 6. Verify ────────────────────────────────────────────────
if grep -qF "$SENTINEL" "$TARGET" 2>/dev/null; then
  printf "\n${BOLD}${GREEN}Done!${RESET}\n"
  printf "  Patched : ${BOLD}%s${RESET}\n" "$TARGET"
  printf "  Backup  : ${BOLD}%s${RESET}\n" "$BACKUP"
  printf "\n${CYAN}Restart VS Code for the changes to take effect.${RESET}\n\n"
else
  cp "$BACKUP" "$TARGET"
  die "Verification failed (minified names may differ) — rolled back to backup."
fi
