#!/bin/bash

# WordLift CLI Global Setup Script

set -e

echo "🚀 Setting up WordLift CLI globally..."

# Get the current directory
CURRENT_DIR="$(pwd)"
WORDLIFT_CLI_PATH="$CURRENT_DIR/bin/wordlift-cli.js"

# Check if the WordLift CLI exists
if [ ! -f "$WORDLIFT_CLI_PATH" ]; then
    echo "❌ WordLift CLI not found at $WORDLIFT_CLI_PATH"
    echo "Please run this script from the WordLift CLI directory."
    exit 1
fi

# Make sure it's executable
chmod +x "$WORDLIFT_CLI_PATH"

# Create a global symlink
GLOBAL_BIN_DIR="/usr/local/bin"
GLOBAL_WORDLIFT_CLI="$GLOBAL_BIN_DIR/wordlift-cli"

if [ -w "$GLOBAL_BIN_DIR" ]; then
    echo "📦 Creating global symlink..."
    ln -sf "$WORDLIFT_CLI_PATH" "$GLOBAL_WORDLIFT_CLI"
    echo "✅ WordLift CLI installed globally as 'wordlift-cli'"
else
    echo "⚠️  Cannot write to $GLOBAL_BIN_DIR. Creating user-local installation..."

    # Create ~/.local/bin if it doesn't exist
    USER_BIN_DIR="$HOME/.local/bin"
    mkdir -p "$USER_BIN_DIR"

    # Create symlink in user's local bin
    USER_WORDLIFT_CLI="$USER_BIN_DIR/wordlift-cli"
    ln -sf "$WORDLIFT_CLI_PATH" "$USER_WORDLIFT_CLI"

    echo "✅ WordLift CLI installed in $USER_BIN_DIR"

    # Check if ~/.local/bin is in PATH
    if [[ ":$PATH:" != *":$USER_BIN_DIR:"* ]]; then
        echo ""
        echo "⚠️  Please add ~/.local/bin to your PATH:"
        echo "   echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.zshrc"
        echo "   source ~/.zshrc"
    fi
fi

# Also create an alias suggestion
echo ""
echo "📋 You can also create an alias by adding this to your ~/.zshrc:"
echo "   alias wordlift='$WORDLIFT_CLI_PATH'"
echo ""
echo "🎉 Setup complete! You can now use WordLift CLI with:"
echo "   wordlift-cli"
echo "   or if you're in the project directory: ./bin/wordlift-cli.js"
echo ""
echo "📖 For the full WordLift branding experience, the CLI will automatically"
echo "    detect and use the modified Gemini installation when available."
