#!/bin/bash

# Graphorama MCP Wrapper Script Generator
# Generates platform-specific wrapper scripts for MCP clients

set -euo pipefail

VERSION="1.0.0"
SCRIPT_NAME=$(basename "$0")

# Default values
BINARY_PATH="/usr/local/bin/graphorama"
OUTPUT_DIR="./wrappers"
PLATFORMS="all"
CONFIG_FILE=""
VERBOSE=false

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

# Print functions
print_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }

# Help function
show_help() {
cat << EOF
$SCRIPT_NAME v$VERSION - Graphorama MCP Wrapper Generator

USAGE:
    $SCRIPT_NAME [OPTIONS]

DESCRIPTION:
    Generates platform-specific wrapper scripts for Graphorama MCP integration.
    Creates optimized scripts for Claude Desktop, Claude Code, Cursor, Windsurf, and Gemini CLI.

OPTIONS:
    -b, --binary-path PATH      Path to graphorama binary (default: /usr/local/bin/graphorama)
    -o, --output-dir DIR        Output directory for wrapper scripts (default: ./wrappers)
    -p, --platforms LIST        Platforms to generate (all|claude-desktop|claude-code|cursor|windsurf|gemini-cli)
    -c, --config FILE           Optional config file for custom settings
    -v, --verbose               Enable verbose output
    -h, --help                  Show this help message
        --version               Show version information

EXAMPLES:
    # Generate all wrappers with default settings
    $SCRIPT_NAME

    # Generate for specific platforms  
    $SCRIPT_NAME --platforms claude-desktop,cursor --binary-path /opt/graphorama/bin/graphorama

    # Generate with custom config
    $SCRIPT_NAME --config ./graphorama.toml --output-dir ./dist/wrappers

    # Verbose output for debugging
    $SCRIPT_NAME --verbose --platforms all

SUPPORTED PLATFORMS:
    claude-desktop  - Claude Desktop JSON configuration + wrapper script
    claude-code     - Claude Code CLI integration script  
    cursor          - Cursor IDE MCP configuration + wrapper
    windsurf        - Windsurf IDE MCP configuration + wrapper
    gemini-cli      - Gemini CLI MCP configuration + wrapper
    all             - Generate for all supported platforms

OUTPUT STRUCTURE:
    ./wrappers/
    ├── claude-desktop/
    │   ├── graphorama-mcp.sh
    │   ├── graphorama-mcp.bat
    │   └── claude_desktop_config.json
    ├── claude-code/
    │   ├── install.sh
    │   └── install.bat
    ├── cursor/
    │   ├── graphorama-mcp.sh
    │   ├── graphorama-mcp.bat  
    │   └── mcp.json
    ├── windsurf/
    │   ├── graphorama-mcp.sh
    │   ├── graphorama-mcp.bat
    │   └── mcp_config.json
    └── gemini-cli/
        ├── graphorama-mcp.sh
        ├── graphorama-mcp.bat
        └── settings.json

EOF
}

# Parse command line arguments
parse_args() {
    while [[ $# -gt 0 ]]; do
        case $1 in
            -b|--binary-path)
                BINARY_PATH="$2"
                shift 2
                ;;
            -o|--output-dir)
                OUTPUT_DIR="$2"
                shift 2
                ;;
            -p|--platforms)
                PLATFORMS="$2"
                shift 2
                ;;
            -c|--config)
                CONFIG_FILE="$2"
                shift 2
                ;;
            -v|--verbose)
                VERBOSE=true
                shift
                ;;
            -h|--help)
                show_help
                exit 0
                ;;
            --version)
                echo "$SCRIPT_NAME v$VERSION"
                exit 0
                ;;
            *)
                print_error "Unknown option: $1"
                echo "Use --help for usage information."
                exit 1
                ;;
        esac
    done
}

# Verbose logging
log_verbose() {
    if [[ "$VERBOSE" == "true" ]]; then
        print_info "$1"
    fi
}

# Validate binary path
validate_binary() {
    log_verbose "Validating binary path: $BINARY_PATH"
    
    if [[ ! -f "$BINARY_PATH" ]]; then
        print_warning "Binary not found at $BINARY_PATH (this is OK if generating for distribution)"
        return 0
    fi
    
    if [[ ! -x "$BINARY_PATH" ]]; then
        print_error "Binary at $BINARY_PATH is not executable"
        return 1
    fi
    
    # Test binary if it exists
    if ! "$BINARY_PATH" --version >/dev/null 2>&1; then
        print_warning "Binary at $BINARY_PATH failed version check"
    else
        log_verbose "Binary validation successful"
    fi
    
    return 0
}

# Create output directories
setup_directories() {
    log_verbose "Setting up output directories in $OUTPUT_DIR"
    
    local platforms_array
    IFS=',' read -ra platforms_array <<< "$PLATFORMS"
    
    mkdir -p "$OUTPUT_DIR"
    
    for platform in "${platforms_array[@]}"; do
        case $platform in
            all)
                mkdir -p "$OUTPUT_DIR"/{claude-desktop,claude-code,cursor,windsurf,gemini-cli}
                break
                ;;
            claude-desktop|claude-code|cursor|windsurf|gemini-cli)
                mkdir -p "$OUTPUT_DIR/$platform"
                ;;
            *)
                print_warning "Unknown platform: $platform"
                ;;
        esac
    done
}

# Generate Claude Desktop wrappers
generate_claude_desktop() {
    local output_dir="$OUTPUT_DIR/claude-desktop"
    print_info "Generating Claude Desktop wrappers in $output_dir"
    
    # Unix wrapper script
    cat > "$output_dir/graphorama-mcp.sh" << 'EOF'
#!/bin/bash
# Graphorama MCP wrapper script for Claude Desktop (Unix/macOS/Linux)
# Generated by graphorama wrapper generator

set -euo pipefail

# Configuration
BINARY_PATH="__BINARY_PATH__"
CONFIG_FILE="__CONFIG_FILE__"

# Validate binary exists
if [[ ! -f "$BINARY_PATH" ]]; then
    echo "❌ Error: Graphorama binary not found at $BINARY_PATH" >&2
    echo "   Please install graphorama or update the BINARY_PATH in this script" >&2
    exit 1
fi

if [[ ! -x "$BINARY_PATH" ]]; then
    echo "❌ Error: Graphorama binary at $BINARY_PATH is not executable" >&2
    echo "   Run: chmod +x $BINARY_PATH" >&2
    exit 1
fi

# Build command arguments
args=("serve" "--transport" "stdio")

# Add config file if specified and exists
if [[ -n "$CONFIG_FILE" && -f "$CONFIG_FILE" ]]; then
    args+=("--config" "$CONFIG_FILE")
fi

# Execute graphorama with proper error handling
exec "$BINARY_PATH" "${args[@]}"
EOF

    # Windows wrapper script
    cat > "$output_dir/graphorama-mcp.bat" << 'EOF'
@echo off
REM Graphorama MCP wrapper script for Claude Desktop (Windows)
REM Generated by graphorama wrapper generator

setlocal EnableDelayedExpansion

REM Configuration
set "BINARY_PATH=__BINARY_PATH__"
set "CONFIG_FILE=__CONFIG_FILE__"

REM Validate binary exists
if not exist "%BINARY_PATH%" (
    echo ❌ Error: Graphorama binary not found at %BINARY_PATH% >&2
    echo    Please install graphorama or update the BINARY_PATH in this script >&2
    exit /b 1
)

REM Build command arguments
set "args=serve --transport stdio"

REM Add config file if specified and exists
if defined CONFIG_FILE (
    if exist "%CONFIG_FILE%" (
        set "args=%args% --config %CONFIG_FILE%"
    )
)

REM Execute graphorama
"%BINARY_PATH%" %args%
EOF

    # Claude Desktop configuration file
    cat > "$output_dir/claude_desktop_config.json" << EOF
{
  "mcpServers": {
    "graphorama": {
      "command": "__WRAPPER_SCRIPT_PATH__"
    }
  }
}
EOF

    # Installation instructions
    cat > "$output_dir/README.md" << 'EOF'
# Claude Desktop Installation

## Quick Setup

### macOS/Linux
1. Copy `graphorama-mcp.sh` to a permanent location (e.g., `/usr/local/bin/`)
2. Make it executable: `chmod +x /usr/local/bin/graphorama-mcp.sh`
3. Edit the `claude_desktop_config.json` and replace `__WRAPPER_SCRIPT_PATH__` with the full path to your wrapper script
4. Add the configuration to your Claude Desktop config file:
   - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
   - Linux: `~/.config/Claude/claude_desktop_config.json`

### Windows
1. Copy `graphorama-mcp.bat` to a permanent location (e.g., `C:\Program Files\graphorama\`)
2. Edit the `claude_desktop_config.json` and replace `__WRAPPER_SCRIPT_PATH__` with the full path to your wrapper script
3. Add the configuration to your Claude Desktop config file:
   - Windows: `%APPDATA%\Claude\claude_desktop_config.json`

## Configuration

Edit the wrapper script to customize:
- `BINARY_PATH`: Path to your graphorama binary
- `CONFIG_FILE`: Optional path to graphorama.toml config file

## Verification

After setup:
1. Restart Claude Desktop
2. Start a new conversation
3. Try: "Can you validate this Python code: print('hello world')"
4. Claude should use the `validate_changes` tool automatically
EOF

    # Make scripts executable
    chmod +x "$output_dir/graphorama-mcp.sh" 2>/dev/null || true
    
    log_verbose "Claude Desktop wrappers generated successfully"
}

# Generate Claude Code wrappers
generate_claude_code() {
    local output_dir="$OUTPUT_DIR/claude-code"
    print_info "Generating Claude Code wrappers in $output_dir"
    
    # Unix installation script
    cat > "$output_dir/install.sh" << 'EOF'
#!/bin/bash
# Claude Code installation script for Graphorama MCP
# Generated by graphorama wrapper generator

set -euo pipefail

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

print_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }

# Configuration
BINARY_PATH="__BINARY_PATH__"
CONFIG_FILE="__CONFIG_FILE__"
SCOPE="${1:-user}"

print_info "Installing Graphorama MCP for Claude Code"
print_info "Binary path: $BINARY_PATH"
print_info "Scope: $SCOPE"

# Validate binary
if [[ ! -f "$BINARY_PATH" ]]; then
    print_warning "Binary not found at $BINARY_PATH"
    echo "Please install graphorama first or update BINARY_PATH in this script"
    exit 1
fi

# Build claude mcp add command
cmd=(claude mcp add graphorama --scope "$SCOPE")

# Add environment variables if config file exists
if [[ -n "$CONFIG_FILE" && -f "$CONFIG_FILE" ]]; then
    cmd+=(--env "GRAPHORAMA_CONFIG=$CONFIG_FILE")
fi

# Add common environment variables for better performance
cmd+=(--env GRAPHORAMA_CACHE_BACKEND=sqlite)
cmd+=(--env GRAPHORAMA_CACHE_TTL=600)

# Add the binary command
cmd+=(-- "$BINARY_PATH" serve --transport stdio)

# Add config file if specified
if [[ -n "$CONFIG_FILE" && -f "$CONFIG_FILE" ]]; then
    cmd+=(--config "$CONFIG_FILE")
fi

# Execute installation
print_info "Running: ${cmd[*]}"
if "${cmd[@]}"; then
    print_success "Graphorama MCP installed successfully!"
    print_info "You can now use graphorama tools in Claude Code conversations"
    print_info "Try: 'Can you validate this code for me: print(\"hello world\")'"
else
    echo "❌ Installation failed. Please check your Claude Code setup and try again."
    exit 1
fi
EOF

    # Windows installation script
    cat > "$output_dir/install.bat" << 'EOF'
@echo off
REM Claude Code installation script for Graphorama MCP (Windows)
REM Generated by graphorama wrapper generator

setlocal EnableDelayedExpansion

REM Configuration
set "BINARY_PATH=__BINARY_PATH__"
set "CONFIG_FILE=__CONFIG_FILE__"
set "SCOPE=%~1"
if "%SCOPE%"=="" set "SCOPE=user"

echo [INFO] Installing Graphorama MCP for Claude Code
echo [INFO] Binary path: %BINARY_PATH%
echo [INFO] Scope: %SCOPE%

REM Validate binary
if not exist "%BINARY_PATH%" (
    echo [WARNING] Binary not found at %BINARY_PATH%
    echo Please install graphorama first or update BINARY_PATH in this script
    exit /b 1
)

REM Build command
set "cmd=claude mcp add graphorama --scope %SCOPE%"

REM Add environment variables
set "cmd=%cmd% --env GRAPHORAMA_CACHE_BACKEND=sqlite"
set "cmd=%cmd% --env GRAPHORAMA_CACHE_TTL=600"

REM Add config file environment if exists
if defined CONFIG_FILE (
    if exist "%CONFIG_FILE%" (
        set "cmd=%cmd% --env GRAPHORAMA_CONFIG=%CONFIG_FILE%"
    )
)

REM Add binary command
set "cmd=%cmd% -- \"%BINARY_PATH%\" serve --transport stdio"

REM Add config file if specified
if defined CONFIG_FILE (
    if exist "%CONFIG_FILE%" (
        set "cmd=%cmd% --config \"%CONFIG_FILE%\""
    )
)

REM Execute installation
echo [INFO] Running: %cmd%
%cmd%

if !errorlevel! equ 0 (
    echo [SUCCESS] Graphorama MCP installed successfully!
    echo [INFO] You can now use graphorama tools in Claude Code conversations
    echo [INFO] Try: "Can you validate this code for me: print('hello world')"
) else (
    echo ❌ Installation failed. Please check your Claude Code setup and try again.
    exit /b 1
)
EOF

    # README with usage instructions
    cat > "$output_dir/README.md" << 'EOF'
# Claude Code Installation

## Quick Setup

### macOS/Linux
```bash
# Make installer executable
chmod +x install.sh

# Install for current user (recommended)
./install.sh user

# Or install for current project only  
./install.sh local

# Or install for team (shared via .mcp.json)
./install.sh project
```

### Windows
```cmd
REM Install for current user (recommended)
install.bat user

REM Or install for current project only
install.bat local

REM Or install for team (shared via .mcp.json)  
install.bat project
```

## Manual Installation

If the automated script doesn't work:

```bash
# Basic installation
claude mcp add graphorama --scope user -- /usr/local/bin/graphorama serve --transport stdio

# With environment variables for better performance
claude mcp add graphorama \
  --scope user \
  --env GRAPHORAMA_CACHE_BACKEND=sqlite \
  --env GRAPHORAMA_CACHE_TTL=600 \
  -- /usr/local/bin/graphorama serve --transport stdio
```

## Verification

After installation:
```bash
# Check MCP status
claude mcp list

# Test with a simple validation
# In Claude Code, try: "Can you validate this Python code: def hello(): return 'world'"
```

## Configuration

Edit the installation script to customize:
- `BINARY_PATH`: Path to your graphorama binary
- `CONFIG_FILE`: Optional path to graphorama.toml config file
- Environment variables for cache settings

## Available Scopes

- `local`: Available only in current project
- `user`: Available across all your projects  
- `project`: Shared with team via .mcp.json file
EOF

    chmod +x "$output_dir/install.sh" 2>/dev/null || true
    
    log_verbose "Claude Code wrappers generated successfully"
}

# Generate Cursor IDE wrappers  
generate_cursor() {
    local output_dir="$OUTPUT_DIR/cursor"
    print_info "Generating Cursor IDE wrappers in $output_dir"
    
    # Unix wrapper script
    cat > "$output_dir/graphorama-mcp.sh" << 'EOF'
#!/bin/bash
# Graphorama MCP wrapper script for Cursor IDE (Unix/macOS/Linux)
# Generated by graphorama wrapper generator

set -euo pipefail

# Configuration
BINARY_PATH="__BINARY_PATH__"
CONFIG_FILE="__CONFIG_FILE__"

# Validate binary exists
if [[ ! -f "$BINARY_PATH" ]]; then
    echo "❌ Error: Graphorama binary not found at $BINARY_PATH" >&2
    exit 1
fi

if [[ ! -x "$BINARY_PATH" ]]; then
    echo "❌ Error: Graphorama binary at $BINARY_PATH is not executable" >&2
    exit 1
fi

# Build arguments
args=("serve" "--transport" "stdio")

# Add config file if specified and exists
if [[ -n "$CONFIG_FILE" && -f "$CONFIG_FILE" ]]; then
    args+=("--config" "$CONFIG_FILE")
fi

# Execute graphorama
exec "$BINARY_PATH" "${args[@]}"
EOF

    # Windows wrapper script
    cat > "$output_dir/graphorama-mcp.bat" << 'EOF'
@echo off
REM Graphorama MCP wrapper script for Cursor IDE (Windows)
REM Generated by graphorama wrapper generator

setlocal EnableDelayedExpansion

REM Configuration
set "BINARY_PATH=__BINARY_PATH__"
set "CONFIG_FILE=__CONFIG_FILE__"

REM Validate binary exists
if not exist "%BINARY_PATH%" (
    echo ❌ Error: Graphorama binary not found at %BINARY_PATH% >&2
    exit /b 1
)

REM Build arguments
set "args=serve --transport stdio"

REM Add config file if specified and exists
if defined CONFIG_FILE (
    if exist "%CONFIG_FILE%" (
        set "args=%args% --config %CONFIG_FILE%"
    )
)

REM Execute graphorama
"%BINARY_PATH%" %args%
EOF

    # Cursor MCP configuration
    cat > "$output_dir/mcp.json" << EOF
{
  "mcpServers": {
    "graphorama": {
      "command": "__WRAPPER_SCRIPT_PATH__",
      "env": {
        "GRAPHORAMA_CACHE_BACKEND": "sqlite",
        "GRAPHORAMA_CACHE_TTL": "600",
        "GRAPHORAMA_LOG_LEVEL": "info"
      }
    }
  }
}
EOF

    # README with installation instructions
    cat > "$output_dir/README.md" << 'EOF'
# Cursor IDE Installation

## Setup Methods

### Method 1: Settings UI (Easiest)
1. Open Cursor IDE
2. Press `Ctrl+Shift+P` → "Cursor Settings" 
3. Click "MCP" in sidebar
4. Click "Create New MCP Server"
5. Name: `graphorama`
6. Command: `/usr/local/bin/graphorama serve --transport stdio`
7. Click "Add"

### Method 2: Project Configuration
1. Copy `mcp.json` to `.cursor/mcp.json` in your project root
2. Edit the file and replace `__WRAPPER_SCRIPT_PATH__` with the full path to your wrapper script
3. Copy `graphorama-mcp.sh` (or `.bat` on Windows) to your project or a permanent location

### Method 3: Global Configuration
1. Copy `mcp.json` to `~/.cursor/mcp.json` (macOS/Linux) or `%APPDATA%\Cursor\mcp.json` (Windows)
2. Edit the file and replace `__WRAPPER_SCRIPT_PATH__` with the full path to your wrapper script
3. Copy `graphorama-mcp.sh` (or `.bat` on Windows) to a permanent location like `/usr/local/bin/`

## Configuration

Edit the wrapper script to customize:
- `BINARY_PATH`: Path to your graphorama binary  
- `CONFIG_FILE`: Optional path to graphorama.toml config file

Edit `mcp.json` to customize environment variables:
- `GRAPHORAMA_CACHE_BACKEND`: "memory", "sqlite", or "redis"
- `GRAPHORAMA_CACHE_TTL`: Cache timeout in seconds
- `GRAPHORAMA_LOG_LEVEL`: "error", "warn", "info", or "debug"

## Verification

After setup:
1. Look for hammer icon in Cursor chat interface
2. Hover over hammer - should show 7 graphorama tools with green dot
3. Test: "Can you validate this TypeScript code: const x: string = 42;"
4. Cursor should use the `validate_changes` tool automatically

## Troubleshooting

- **No hammer icon**: Check MCP settings, restart Cursor
- **Red dot on tools**: Check wrapper script path and permissions
- **Tools not executing**: Verify binary path and make wrapper executable
EOF

    chmod +x "$output_dir/graphorama-mcp.sh" 2>/dev/null || true
    
    log_verbose "Cursor IDE wrappers generated successfully"
}

# Generate Windsurf IDE wrappers
generate_windsurf() {
    local output_dir="$OUTPUT_DIR/windsurf"
    print_info "Generating Windsurf IDE wrappers in $output_dir"
    
    # Unix wrapper script (similar to Cursor but for Windsurf)
    cat > "$output_dir/graphorama-mcp.sh" << 'EOF'
#!/bin/bash
# Graphorama MCP wrapper script for Windsurf IDE (Unix/macOS/Linux)
# Generated by graphorama wrapper generator

set -euo pipefail

# Configuration  
BINARY_PATH="__BINARY_PATH__"
CONFIG_FILE="__CONFIG_FILE__"

# Validate binary exists
if [[ ! -f "$BINARY_PATH" ]]; then
    echo "❌ Error: Graphorama binary not found at $BINARY_PATH" >&2
    exit 1
fi

if [[ ! -x "$BINARY_PATH" ]]; then
    echo "❌ Error: Graphorama binary at $BINARY_PATH is not executable" >&2
    exit 1
fi

# Build arguments
args=("serve" "--transport" "stdio")

# Add config file if specified and exists
if [[ -n "$CONFIG_FILE" && -f "$CONFIG_FILE" ]]; then
    args+=("--config" "$CONFIG_FILE")
fi

# Execute graphorama
exec "$BINARY_PATH" "${args[@]}"
EOF

    # Windows wrapper script
    cat > "$output_dir/graphorama-mcp.bat" << 'EOF'
@echo off
REM Graphorama MCP wrapper script for Windsurf IDE (Windows)
REM Generated by graphorama wrapper generator

setlocal EnableDelayedExpansion

REM Configuration
set "BINARY_PATH=__BINARY_PATH__"
set "CONFIG_FILE=__CONFIG_FILE__"

REM Validate binary exists
if not exist "%BINARY_PATH%" (
    echo ❌ Error: Graphorama binary not found at %BINARY_PATH% >&2
    exit /b 1
)

REM Build arguments
set "args=serve --transport stdio"

REM Add config file if specified and exists
if defined CONFIG_FILE (
    if exist "%CONFIG_FILE%" (
        set "args=%args% --config %CONFIG_FILE%"
    )
)

REM Execute graphorama
"%BINARY_PATH%" %args%
EOF

    # Windsurf MCP configuration
    cat > "$output_dir/mcp_config.json" << EOF
{
  "mcpServers": {
    "graphorama": {
      "command": "__WRAPPER_SCRIPT_PATH__",
      "env": {
        "GRAPHORAMA_CACHE_BACKEND": "sqlite",
        "GRAPHORAMA_CACHE_TTL": "600",
        "GRAPHORAMA_LOG_LEVEL": "info"
      }
    }
  }
}
EOF

    # README with installation instructions
    cat > "$output_dir/README.md" << 'EOF'
# Windsurf IDE Installation

## Setup Methods

### Method 1: Settings UI (Recommended)
1. Open Windsurf IDE
2. Go to `Windsurf → Settings → Advanced Settings`
3. Scroll to "Cascade" section
4. Click "Add New Server"
5. Name: `graphorama`  
6. Command: `/usr/local/bin/graphorama serve --transport stdio`
7. Click "Save"

### Method 2: Chat Interface
1. Open Windsurf Chat
2. Click "+ Configure MCP" 
3. Add New Server:
   - Server Name: `graphorama`
   - Command: `/usr/local/bin/graphorama serve --transport stdio`
4. Save configuration

### Method 3: Manual Configuration
1. Copy `mcp_config.json` to `~/.codeium/windsurf/mcp_config.json`
2. Edit the file and replace `__WRAPPER_SCRIPT_PATH__` with the full path to your wrapper script
3. Copy `graphorama-mcp.sh` (or `.bat` on Windows) to a permanent location

## Configuration

Edit the wrapper script to customize:
- `BINARY_PATH`: Path to your graphorama binary
- `CONFIG_FILE`: Optional path to graphorama.toml config file

Edit `mcp_config.json` to customize environment variables:
- `GRAPHORAMA_CACHE_BACKEND`: "memory", "sqlite", or "redis"
- `GRAPHORAMA_CACHE_TTL`: Cache timeout in seconds
- `GRAPHORAMA_LOG_LEVEL`: "error", "warn", "info", or "debug"

## Verification

After setup:
1. Look for hammer icon in Cascade toolbar
2. Hover over hammer - should show 7 graphorama tools with green dot
3. Test: "Can you validate this Python code: def hello(): return 'world'"
4. Cascade should use the `validate_changes` tool automatically

## Pro Tips

- Only enable MCP servers you need - too many can confuse Cascade
- Use @graphorama to target tools directly: "Use @graphorama to validate this file"  
- Enable auto-run to skip tool confirmation prompts
- Check logs at `~/.codeium/windsurf/logs/` for debugging

## Troubleshooting

- **No hammer icon**: Check MCP settings, restart Windsurf
- **Red dot on tools**: Check wrapper script path and permissions  
- **Tools not executing**: Verify binary path and make wrapper executable
- **Configuration errors**: Validate JSON syntax of mcp_config.json
EOF

    chmod +x "$output_dir/graphorama-mcp.sh" 2>/dev/null || true
    
    log_verbose "Windsurf IDE wrappers generated successfully"
}

# Generate Gemini CLI wrappers
generate_gemini_cli() {
    local output_dir="$OUTPUT_DIR/gemini-cli"
    print_info "Generating Gemini CLI wrappers in $output_dir"
    
    # Unix wrapper script  
    cat > "$output_dir/graphorama-mcp.sh" << 'EOF'
#!/bin/bash
# Graphorama MCP wrapper script for Gemini CLI (Unix/macOS/Linux)
# Generated by graphorama wrapper generator

set -euo pipefail

# Configuration
BINARY_PATH="__BINARY_PATH__"
CONFIG_FILE="__CONFIG_FILE__"

# Validate binary exists
if [[ ! -f "$BINARY_PATH" ]]; then
    echo "❌ Error: Graphorama binary not found at $BINARY_PATH" >&2
    exit 1
fi

if [[ ! -x "$BINARY_PATH" ]]; then
    echo "❌ Error: Graphorama binary at $BINARY_PATH is not executable" >&2
    exit 1
fi

# Build arguments
args=("serve" "--transport" "stdio")

# Add config file if specified and exists
if [[ -n "$CONFIG_FILE" && -f "$CONFIG_FILE" ]]; then
    args+=("--config" "$CONFIG_FILE")
fi

# Execute graphorama
exec "$BINARY_PATH" "${args[@]}"
EOF

    # Windows wrapper script
    cat > "$output_dir/graphorama-mcp.bat" << 'EOF'
@echo off
REM Graphorama MCP wrapper script for Gemini CLI (Windows)  
REM Generated by graphorama wrapper generator

setlocal EnableDelayedExpansion

REM Configuration
set "BINARY_PATH=__BINARY_PATH__"
set "CONFIG_FILE=__CONFIG_FILE__"

REM Validate binary exists
if not exist "%BINARY_PATH%" (
    echo ❌ Error: Graphorama binary not found at %BINARY_PATH% >&2
    exit /b 1
)

REM Build arguments
set "args=serve --transport stdio"

REM Add config file if specified and exists  
if defined CONFIG_FILE (
    if exist "%CONFIG_FILE%" (
        set "args=%args% --config %CONFIG_FILE%"
    )
)

REM Execute graphorama
"%BINARY_PATH%" %args%
EOF

    # Gemini CLI settings configuration
    cat > "$output_dir/settings.json" << EOF
{
  "McpServers": {
    "graphorama": {
      "command": "__WRAPPER_SCRIPT_PATH__",
      "timeout": 15000,
      "trust": false,
      "env": {
        "GRAPHORAMA_CACHE_BACKEND": "sqlite",
        "GRAPHORAMA_CACHE_TTL": "600",
        "GRAPHORAMA_LOG_LEVEL": "info"
      }
    }
  }
}
EOF

    # README with installation instructions
    cat > "$output_dir/README.md" << 'EOF'
# Gemini CLI Installation

## Setup

### Find Your Settings File
```bash
# Find settings file location
gemini config --show-path

# Common locations:
# macOS: ~/.config/gemini-cli/settings.json
# Linux: ~/.config/gemini-cli/settings.json  
# Windows: %APPDATA%/gemini-cli/settings.json
```

### Installation Steps
1. Copy the `settings.json` content to your Gemini CLI settings file
2. Replace `__WRAPPER_SCRIPT_PATH__` with the full path to your wrapper script
3. Copy `graphorama-mcp.sh` (or `.bat` on Windows) to a permanent location like `/usr/local/bin/`
4. Make the wrapper script executable: `chmod +x /usr/local/bin/graphorama-mcp.sh`

### Alternative: Manual Configuration
Add this to your existing `settings.json`:

```json
{
  "McpServers": {
    "graphorama": {
      "command": "/usr/local/bin/graphorama",
      "args": ["serve", "--transport", "stdio"],
      "timeout": 15000,
      "trust": false,
      "env": {
        "GRAPHORAMA_CACHE_BACKEND": "sqlite",
        "GRAPHORAMA_CACHE_TTL": "600"
      }
    }
  }
}
```

## Configuration Options

Edit the wrapper script to customize:
- `BINARY_PATH`: Path to your graphorama binary
- `CONFIG_FILE`: Optional path to graphorama.toml config file

Edit `settings.json` to customize:
- `timeout`: Request timeout in milliseconds (default: 15000)
- `trust`: Skip tool confirmation if true (default: false)
- `includeTools`: Whitelist specific tools (optional)
- `excludeTools`: Blacklist specific tools (optional)
- Environment variables for performance tuning

## Advanced Configuration

### Tool Filtering
```json
{
  "McpServers": {
    "graphorama": {
      "command": "/usr/local/bin/graphorama-mcp.sh",
      "includeTools": [
        "validate_changes",
        "discover_services", 
        "get_cache_stats"
      ]
    }
  }
}
```

### Performance Tuning
```json
{
  "env": {
    "GRAPHORAMA_CACHE_BACKEND": "sqlite",
    "GRAPHORAMA_CACHE_TTL": "1800",
    "GRAPHORAMA_MAX_FILE_SIZE": "5242880",
    "GRAPHORAMA_TIMEOUT": "20"
  }
}
```

## Verification

After setup:
```bash
# List configured MCP servers
gemini mcp list

# Test connection
gemini mcp test graphorama

# Start conversation and test
gemini chat
> "Can you validate this JavaScript: const x = 42; console.log(x);"
```

## Usage Examples

### Interactive Mode
```bash
gemini chat
> "Validate all Python files in my project"
> "What services are running in Docker?"
> "Check if my API changes will break other services"
```

### Command Line Integration  
```bash
# Validate specific files
gemini chat --message "Validate these TypeScript files: $(find src/ -name '*.ts')"

# Service discovery
gemini chat --message "List all running services with health status"

# Batch processing
for file in src/*.py; do
    gemini chat --message "Validate $file for issues" --no-interactive
done
```

## Troubleshooting

- **MCP Server Not Found**: Check settings file location and JSON syntax
- **Tools Not Loading**: Verify wrapper script path and binary permissions
- **Timeout Issues**: Increase timeout value or optimize cache settings  
- **Permission Errors**: Make wrapper script executable and check binary path
EOF

    chmod +x "$output_dir/graphorama-mcp.sh" 2>/dev/null || true
    
    log_verbose "Gemini CLI wrappers generated successfully"
}

# Replace placeholders in generated files
replace_placeholders() {
    log_verbose "Replacing placeholders in generated files"
    
    local config_arg=""
    if [[ -n "$CONFIG_FILE" ]]; then
        config_arg="$CONFIG_FILE"
    fi
    
    # Find all generated files and replace placeholders
    find "$OUTPUT_DIR" -type f \( -name "*.sh" -o -name "*.bat" -o -name "*.json" \) -exec sed -i.bak \
        -e "s|__BINARY_PATH__|$BINARY_PATH|g" \
        -e "s|__CONFIG_FILE__|$config_arg|g" \
        -e "s|__WRAPPER_SCRIPT_PATH__|REPLACE_WITH_ACTUAL_PATH|g" \
        {} + 2>/dev/null || true
    
    # Clean up backup files
    find "$OUTPUT_DIR" -name "*.bak" -delete 2>/dev/null || true
    
    log_verbose "Placeholder replacement completed"
}

# Generate wrappers for specified platforms
generate_wrappers() {
    local platforms_array
    IFS=',' read -ra platforms_array <<< "$PLATFORMS"
    
    for platform in "${platforms_array[@]}"; do
        case $platform in
            all)
                generate_claude_desktop
                generate_claude_code
                generate_cursor
                generate_windsurf  
                generate_gemini_cli
                break
                ;;
            claude-desktop)
                generate_claude_desktop
                ;;
            claude-code)
                generate_claude_code
                ;;
            cursor)
                generate_cursor
                ;;
            windsurf)
                generate_windsurf
                ;;
            gemini-cli)
                generate_gemini_cli
                ;;
            *)
                print_warning "Unknown platform: $platform (skipping)"
                ;;
        esac
    done
}

# Generate master installation script
generate_master_installer() {
    log_verbose "Generating master installation script"
    
    cat > "$OUTPUT_DIR/install-graphorama.sh" << 'EOF'
#!/bin/bash
# Graphorama MCP Master Installer
# Auto-detects platforms and installs appropriate wrappers

set -euo pipefail

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

print_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
print_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
print_error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }

# Detect available MCP clients
detect_platforms() {
    local platforms=()
    
    # Check for Claude Desktop
    if [[ -d "$HOME/Library/Application Support/Claude" ]] || [[ -d "$HOME/.config/Claude" ]]; then
        platforms+=("claude-desktop")
    fi
    
    # Check for Claude Code
    if command -v claude >/dev/null 2>&1; then
        platforms+=("claude-code")
    fi
    
    # Check for Cursor
    if [[ -d "$HOME/.cursor" ]] || command -v cursor >/dev/null 2>&1; then
        platforms+=("cursor")
    fi
    
    # Check for Windsurf
    if [[ -d "$HOME/.codeium/windsurf" ]] || command -v windsurf >/dev/null 2>&1; then
        platforms+=("windsurf")
    fi
    
    # Check for Gemini CLI
    if command -v gemini >/dev/null 2>&1; then
        platforms+=("gemini-cli")
    fi
    
    printf '%s\n' "${platforms[@]}"
}

# Main installation logic
main() {
    print_info "🚀 Graphorama MCP Master Installer"
    print_info "Detecting available MCP clients..."
    
    local platforms
    readarray -t platforms < <(detect_platforms)
    
    if [[ ${#platforms[@]} -eq 0 ]]; then
        print_warning "No supported MCP clients found"
        echo "Supported clients: Claude Desktop, Claude Code, Cursor IDE, Windsurf IDE, Gemini CLI"
        exit 1
    fi
    
    print_success "Found ${#platforms[@]} MCP client(s): ${platforms[*]}"
    
    # Install for each detected platform
    for platform in "${platforms[@]}"; do
        print_info "Installing for $platform..."
        if [[ -d "./$platform" ]]; then
            case $platform in
                claude-desktop)
                    print_info "Please manually configure Claude Desktop using files in ./claude-desktop/"
                    ;;
                claude-code)
                    if [[ -x "./claude-code/install.sh" ]]; then
                        ./claude-code/install.sh
                    fi
                    ;;
                cursor)
                    print_info "Please manually configure Cursor IDE using files in ./cursor/"
                    ;;
                windsurf)
                    print_info "Please manually configure Windsurf IDE using files in ./windsurf/"
                    ;;
                gemini-cli)
                    print_info "Please manually configure Gemini CLI using files in ./gemini-cli/"
                    ;;
            esac
        else
            print_warning "No installation files found for $platform"
        fi
    done
    
    print_success "🎉 Installation complete!"
    print_info "Check the README.md files in each platform directory for setup instructions"
}

main "$@"
EOF

    chmod +x "$OUTPUT_DIR/install-graphorama.sh" 2>/dev/null || true
}

# Generate comprehensive README
generate_readme() {
    log_verbose "Generating comprehensive README"
    
    cat > "$OUTPUT_DIR/README.md" << 'EOF'
# 🚀 Graphorama MCP Wrappers

This directory contains platform-specific wrapper scripts and configurations for integrating Graphorama with various MCP clients.

## 📦 Generated Files

```
wrappers/
├── install-graphorama.sh          # Master installer (auto-detects platforms)
├── claude-desktop/                # Claude Desktop integration
│   ├── graphorama-mcp.sh         # Unix wrapper script
│   ├── graphorama-mcp.bat        # Windows wrapper script
│   ├── claude_desktop_config.json # Configuration template
│   └── README.md                  # Setup instructions
├── claude-code/                   # Claude Code integration
│   ├── install.sh                 # Unix installer
│   ├── install.bat                # Windows installer
│   └── README.md                  # Setup instructions
├── cursor/                        # Cursor IDE integration
│   ├── graphorama-mcp.sh         # Unix wrapper script
│   ├── graphorama-mcp.bat        # Windows wrapper script
│   ├── mcp.json                   # Configuration template
│   └── README.md                  # Setup instructions
├── windsurf/                      # Windsurf IDE integration
│   ├── graphorama-mcp.sh         # Unix wrapper script
│   ├── graphorama-mcp.bat        # Windows wrapper script
│   ├── mcp_config.json            # Configuration template
│   └── README.md                  # Setup instructions
└── gemini-cli/                    # Gemini CLI integration
    ├── graphorama-mcp.sh         # Unix wrapper script
    ├── graphorama-mcp.bat        # Windows wrapper script
    ├── settings.json              # Configuration template
    └── README.md                  # Setup instructions
```

## 🚀 Quick Start

### Option 1: Auto-Installation
```bash
# Run the master installer (detects your platforms automatically)
./install-graphorama.sh
```

### Option 2: Platform-Specific Installation
Choose your MCP client and follow the README in the respective directory:

- **[Claude Desktop](./claude-desktop/README.md)** - Desktop app integration
- **[Claude Code](./claude-code/README.md)** - CLI integration with automatic setup
- **[Cursor IDE](./cursor/README.md)** - IDE integration with settings UI
- **[Windsurf IDE](./windsurf/README.md)** - IDE integration with Cascade
- **[Gemini CLI](./gemini-cli/README.md)** - Command-line integration

## 🔧 Configuration

### Before Installation

1. **Install Graphorama Binary**
   ```bash
   # Download from releases or build from source
   curl -L https://github.com/nedops/grapharoma-mcp/releases/latest/download/graphorama-$(uname -m)-$(uname -s | tr '[:upper:]' '[:lower:]') -o graphorama
   chmod +x graphorama
   sudo mv graphorama /usr/local/bin/
   ```

2. **Update Wrapper Scripts (if needed)**
   Edit the wrapper scripts to customize:
   - `BINARY_PATH`: Path to your graphorama binary
   - `CONFIG_FILE`: Path to your graphorama.toml config (optional)

3. **Create Config File (optional)**
   ```toml
   # graphorama.toml
   [validation]
   languages = ["typescript", "python", "rust"]
   auto_run_tests = true
   
   [cache]
   backend = "sqlite"
   ttl_seconds = 600
   
   [discovery]
   sources = ["docker", "process"]
   ```

## 🎯 Available Tools

Once installed, Graphorama provides these 7 MCP tools:

1. **`validate_changes`** - Code validation with intelligent caching
2. **`discover_services`** - Multi-source service discovery
3. **`validate_cross_service`** - Cross-service breaking change detection
4. **`run_integration_tests`** - Multi-service test orchestration
5. **`get_cache_stats`** - Cache performance metrics
6. **`watch_path`** - File system monitoring with auto-validation
7. **`validate_contract`** - API contract validation

## ✅ Verification

After installation, test with any of these prompts:

```
"Can you validate this Python code for me: print('hello world')"
"What services are currently running on my system?"
"Validate all TypeScript files in my src/ directory"
"Check my cache performance stats"
```

## 🔧 Troubleshooting

### Common Issues

1. **Binary not found**
   - Ensure graphorama is installed and in PATH
   - Update `BINARY_PATH` in wrapper scripts

2. **Permission denied**
   ```bash
   chmod +x /usr/local/bin/graphorama
   chmod +x ./*/graphorama-mcp.sh
   ```

3. **Tools not loading**
   - Check MCP client logs
   - Verify wrapper script paths
   - Restart MCP client

4. **Configuration errors**
   - Validate JSON syntax in config files
   - Check file paths in configurations

### Platform-Specific Issues

Each platform directory contains detailed troubleshooting information in its README.md file.

## 🔄 Updates

When updating Graphorama:
1. Download new binary and replace existing one
2. Regenerate wrappers if needed
3. Restart MCP clients to reconnect

## 📚 Documentation

- [Platform-specific guides](../docs/quick-start/)
- [Configuration reference](../docs/configuration.md)
- [Troubleshooting guide](../docs/troubleshooting.md)
- [Performance tuning](../docs/performance-tuning.md)

---

**Generated by Graphorama Wrapper Generator v1.0.0**
EOF
}

# Main execution
main() {
    print_info "🚀 Graphorama MCP Wrapper Generator v$VERSION"
    
    # Parse arguments
    parse_args "$@"
    
    # Validate inputs
    if ! validate_binary; then
        exit 1
    fi
    
    # Setup directories  
    setup_directories
    
    # Generate wrappers
    print_info "Generating wrappers for platforms: $PLATFORMS"
    generate_wrappers
    
    # Replace placeholders
    replace_placeholders
    
    # Generate additional files
    generate_master_installer
    generate_readme
    
    print_success "🎉 Wrapper generation complete!"
    print_info "Output directory: $OUTPUT_DIR"
    print_info "Run ./install-graphorama.sh for auto-installation"
    
    # Show summary
    echo
    echo "📁 Generated files:"
    find "$OUTPUT_DIR" -type f | sort | sed 's/^/  /'
}

# Run main function with all arguments
main "$@"