#!/bin/bash
#
# codevibe - CodeVibe CLI
#
# Manages authentication, updates, and plugin lifecycle.
# Authentication is shared across all CodeVibe plugins (Claude, Codex, Gemini).
#
# Usage:
#   codevibe login              # Sign in via browser
#   codevibe logout             # Sign out
#   codevibe status             # Show auth status
#   codevibe update             # Update all CodeVibe packages + Claude plugin
#   codevibe version            # Show installed versions
#   codevibe reset-device       # Reset device identity (destructive)
#   codevibe --help             # Show this help
#
# Environment:
#   ENVIRONMENT                 # Set to 'production' (default) or 'development'
#

export ENVIRONMENT="${ENVIRONMENT:-production}"

# Colors
PURPLE='\033[0;35m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'

# Resolve symlinks to find the actual script location
SOURCE="${BASH_SOURCE[0]}"
while [ -L "$SOURCE" ]; do
  DIR="$(cd "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ "$SOURCE" != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd "$(dirname "$SOURCE")" && pwd)"
PACKAGE_DIR="$(dirname "$SCRIPT_DIR")"

# ─── Help ────────────────────────────────────────────────────────────

show_help() {
  echo ""
  echo -e "${BOLD}CodeVibe${NC} — Control AI coding agents from your phone"
  echo ""
  echo "Usage: codevibe <command>"
  echo ""
  echo "Commands:"
  echo "  login          Sign in with Apple or Google (opens browser)"
  echo "  logout         Sign out"
  echo "  status         Show authentication status"
  echo "  update         Update all CodeVibe packages and Claude plugin"
  echo "  version        Show installed package versions"
  echo "  reset-device   Reset device identity (destructive)"
  echo ""
  echo "Agent wrappers:"
  echo "  codevibe-claude    Start Claude Code with mobile sync"
  echo "  codevibe-gemini    Start Gemini CLI with mobile sync"
  echo "  codevibe-codex     Start Codex CLI with mobile sync"
  echo ""
  echo -e "${DIM}https://quantiya.ai/codevibe${NC}"
  echo ""
}

# ─── Version ─────────────────────────────────────────────────────────

show_version() {
  echo ""
  echo -e "${BOLD}CodeVibe Versions${NC}"
  echo ""

  # Meta-package version
  if [ -f "$PACKAGE_DIR/package.json" ]; then
    META_VER=$(node -p "require('$PACKAGE_DIR/package.json').version" 2>/dev/null || echo "?")
    echo -e "  @quantiya/codevibe              ${GREEN}$META_VER${NC}"
  fi

  # Core version
  CORE_PKG="$PACKAGE_DIR/node_modules/@quantiya/codevibe-core/package.json"
  if [ -f "$CORE_PKG" ]; then
    CORE_VER=$(node -p "require('$CORE_PKG').version" 2>/dev/null || echo "?")
    echo -e "  @quantiya/codevibe-core          ${GREEN}$CORE_VER${NC}"
  fi

  # Plugin versions
  for plugin in claude gemini codex; do
    PKG="$PACKAGE_DIR/node_modules/@quantiya/codevibe-${plugin}-plugin/package.json"
    if [ -f "$PKG" ]; then
      VER=$(node -p "require('$PKG').version" 2>/dev/null || echo "?")
      echo -e "  @quantiya/codevibe-${plugin}-plugin  ${GREEN}$VER${NC}"
    fi
  done

  # Claude Code version
  if command -v claude >/dev/null 2>&1; then
    CLAUDE_VER=$(claude --version 2>/dev/null | head -1 || echo "?")
    echo ""
    echo -e "  Claude Code                      ${GREEN}$CLAUDE_VER${NC}"
  fi

  echo ""
}

# ─── Update ──────────────────────────────────────────────────────────

do_update() {
  echo ""
  echo -e "${BOLD}${PURPLE}CodeVibe Update${NC}"
  echo ""

  # Show current versions
  if [ -f "$PACKAGE_DIR/package.json" ]; then
    CUR_VER=$(node -p "require('$PACKAGE_DIR/package.json').version" 2>/dev/null || echo "?")
    echo -e "  ${DIM}Current version: $CUR_VER${NC}"
  fi
  echo ""

  # Update meta-package (pulls latest core + all plugins)
  echo -e "${PURPLE}▸${NC} Updating @quantiya/codevibe..."
  npm install -g --force @quantiya/codevibe@latest 2>&1 | tail -1
  echo -e "${GREEN}✓${NC} CodeVibe updated"

  # Update Claude plugin in Claude Code
  if command -v claude >/dev/null 2>&1; then
    echo ""
    echo -e "${PURPLE}▸${NC} Updating Claude Code plugin..."

    # Refresh marketplace
    if claude plugin marketplace update codevibe-marketplace 2>/dev/null; then
      echo -e "${GREEN}✓${NC} Marketplace refreshed"
    else
      echo -e "${YELLOW}!${NC} Marketplace refresh skipped"
    fi

    # Reinstall plugin (gets latest version from marketplace)
    if claude plugin install codevibe-claude@codevibe-marketplace 2>/dev/null; then
      echo -e "${GREEN}✓${NC} Claude plugin updated"
    else
      echo -e "${YELLOW}!${NC} Claude plugin update skipped"
    fi
  fi

  echo ""

  # Show new versions
  echo -e "${BOLD}Updated versions:${NC}"
  show_version
}

# ─── Command routing ─────────────────────────────────────────────────

case "$1" in
  --help|-h|help|"")
    show_help
    exit 0
    ;;
  version|--version|-v)
    show_version
    exit 0
    ;;
  update)
    do_update
    exit $?
    ;;
  login|logout|status|reset-device)
    # Delegate to codevibe-core CLI
    CORE_CLI="$PACKAGE_DIR/node_modules/@quantiya/codevibe-core/bin/codevibe.js"
    if [ -f "$CORE_CLI" ]; then
      exec node "$CORE_CLI" "$@"
    else
      echo "Error: @quantiya/codevibe-core not found. Try reinstalling: npm install -g @quantiya/codevibe" >&2
      exit 1
    fi
    ;;
  *)
    echo "Unknown command: $1" >&2
    echo "Run 'codevibe --help' for usage." >&2
    exit 1
    ;;
esac
