#!/usr/bin/env bash
################################################################################
# Claude Code Customizations Exporter
# This script packages all customizations for transfer to another machine
################################################################################

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Configuration
CLAUDE_DIR="$HOME/.claude"
EXPORT_DIR="$HOME/claude-customizations-export"
EXPORT_FILE="$HOME/claude-customizations-$(date +%Y%m%d_%H%M%S).tar.gz"

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

# Create export directory
log_info "Creating export directory..."
rm -rf "$EXPORT_DIR"
mkdir -p "$EXPORT_DIR"

# Export agents
log_info "Exporting custom agents..."
mkdir -p "$EXPORT_DIR/agents"
cp -r "$CLAUDE_DIR/agents/"* "$EXPORT_DIR/agents/" 2>/dev/null || true

# Export plugins configuration
log_info "Exporting plugins configuration..."
mkdir -p "$EXPORT_DIR/plugins"
cp -r "$CLAUDE_DIR/plugins/cache/"* "$EXPORT_DIR/plugins/" 2>/dev/null || true
cp "$CLAUDE_DIR/plugins/installed_plugins.json" "$EXPORT_DIR/plugins/" 2>/dev/null || true
cp "$CLAUDE_DIR/plugins/known_marketplaces.json" "$EXPORT_DIR/plugins/" 2>/dev/null || true

# Export settings (without sensitive data)
log_info "Exporting settings..."
mkdir -p "$EXPORT_DIR/config"

# Export settings.local.json (permissions)
cp "$CLAUDE_DIR/settings.local.json" "$EXPORT_DIR/config/" 2>/dev/null || true

# Create settings template (without actual API token)
cat > "$EXPORT_DIR/config/settings-template.json" << EOF
{
  "env": {
    "ANTHROPIC_AUTH_TOKEN": "YOUR_API_TOKEN_HERE",
    "ANTHROPIC_BASE_URL": "https://api.anthropic.com",
    "API_TIMEOUT_MS": "3000000",
    "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1"
  },
  "enabledPlugins": {
    "glm-plan-bug@zai-coding-plugins": true,
    "glm-plan-usage@zai-coding-plugins": true
  }
}
EOF

# Export hooks if present
log_info "Exporting hooks..."
if [ -d "$CLAUDE_DIR/hooks" ] && [ "$(ls -A $CLAUDE_DIR/hooks)" ]; then
    mkdir -p "$EXPORT_DIR/hooks"
    cp -r "$CLAUDE_DIR/hooks/"* "$EXPORT_DIR/hooks/"
fi

# Create README
log_info "Creating documentation..."
cat > "$EXPORT_DIR/README.md" << 'EOF'
# Claude Code Customizations Package

This package contains all customizations for Claude Code including custom agents, MCP tools configuration, and plugins.

## Contents

- `agents/` - Custom agent definitions organized by category
- `plugins/` - Plugin configurations
- `config/` - Settings files
- `hooks/` - Custom hooks (if any)

## Installation

### Quick Install

Run the automated installer:

```bash
bash install-claude-customizations.sh
```

### Manual Install

1. **Copy agents:**
   ```bash
   cp -r agents/* ~/.claude/agents/
   ```

2. **Copy plugins:**
   ```bash
   cp -r plugins/* ~/.claude/plugins/
   ```

3. **Configure settings:**
   ```bash
   cp config/settings.local.json ~/.claude/
   # Edit ~/.claude/settings.json and add your API token
   ```

4. **Install MCP tools:**
   ```bash
   npm install -g @z_ai/mcp-server @z_ai/coding-helper
   ```

5. **Restart Claude Code**

## Agent Categories

- **Engineering** - AI engineer, backend architect, frontend developer, DevOps, mobile app builder
- **Marketing** - TikTok strategist, growth hacker, content creator
- **Product** - Sprint prioritizer, feedback synthesizer, trend researcher
- **Studio Operations** - Studio producer, project shipper, analytics, finance
- **Project Management** - Experiment tracker, studio coach
- **Testing** - Test writer/fixer, API tester, performance benchmarker
- **Design** - UI designer, UX researcher, brand guardian, whimsy injector
- **Bonus** - Joker, studio coach

## MCP Tools Included

- **zai-mcp-server** - Vision analysis (images, videos, UI screenshots, error diagnosis)
- **web-search-prime** - Enhanced web search with domain filtering
- **web-reader** - Fetch URLs and convert to markdown
- **zread** - GitHub repository reader

## Skills

- `glm-plan-bug:case-feedback` - Submit bug/issue feedback
- `glm-plan-usage:usage-query` - Query account usage statistics

## Customization

Edit agent `.md` files in `~/.claude/agents/` to customize agent behavior.

## Support

For issues or questions, refer to the original source machine or Claude Code documentation.
EOF

# Create manifest
log_info "Creating package manifest..."
cat > "$EXPORT_DIR/MANIFEST.json" << EOF
{
  "package": "claude-code-customizations",
  "version": "1.0.0",
  "exported_at": "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)",
  "contents": {
    "agents": "$(ls -1 "$EXPORT_DIR/agents" | wc -l) categories",
    "plugins": "$(ls -1 "$EXPORT_DIR/plugins" 2>/dev/null | wc -l) items",
    "config_files": "$(ls -1 "$EXPORT_DIR/config" | wc -l) files"
  },
  "mcp_tools": [
    "zai-mcp-server (vision)",
    "web-search-prime",
    "web-reader",
    "zread"
  ],
  "skills": [
    "glm-plan-bug:case-feedback",
    "glm-plan-usage:usage-query"
  ]
}
EOF

# Create tarball
log_info "Creating compressed archive..."
tar -czf "$EXPORT_FILE" -C "$HOME" "$(basename "$EXPORT_DIR")"

# Get file size
FILE_SIZE=$(du -h "$EXPORT_FILE" | cut -f1)

log_success "═══════════════════════════════════════════════════════════"
log_success "Export completed successfully!"
log_success "═══════════════════════════════════════════════════════════"
echo ""
log_info "Export location: $EXPORT_FILE"
log_info "Package size: $FILE_SIZE"
log_info "Unpacked directory: $EXPORT_DIR"
echo ""
log_info "To transfer to another machine:"
echo "  1. Copy the archive: scp $EXPORT_FILE user@target:~/"
echo "  2. Extract: tar -xzf $(basename "$EXPORT_FILE")"
echo "  3. Run: cd $(basename "$EXPORT_DIR") && bash install-claude-customizations.sh"
echo ""

# Ask if user wants to keep unpacked directory
read -p "Keep unpacked export directory? (y/N): " keep_unpacked
if [[ ! "$keep_unpacked" =~ ^[Yy]$ ]]; then
    rm -rf "$EXPORT_DIR"
    log_info "Unpacked directory removed"
fi
