#!/usr/bin/env bash
# pipx-install-local - Install claude-mpm from local source to any directory using pipx

set -e

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

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Default values
INSTALL_DIR=""
FORCE=false
VERBOSE=false
EDITABLE=true
SOURCE_DIR=""

# Function to print colored output
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"
}

# Function to show usage
show_usage() {
    cat << EOF
Usage: $0 [OPTIONS] [INSTALL_DIR]

Install claude-mpm from local source using pipx.

OPTIONS:
    -f, --force         Force reinstall if already exists
    -v, --verbose       Verbose output
    --no-editable       Install as regular package (not editable)
    -s, --source PATH   Path to claude-mpm source directory (default: auto-detect)
    -h, --help         Show this help message

INSTALL_DIR:
    Target directory for installation. If not provided, installs to default pipx location.

EXAMPLES:
    # Install to default pipx location (editable)
    $0

    # Install to specific directory (editable)
    $0 /path/to/project

    # Install to current directory (editable)
    $0 .

    # Install from different source directory
    $0 --source /Users/masa/Projects/claude-mpm /path/to/project

    # Force reinstall
    $0 --force /path/to/project

    # Install as regular package (not editable)
    $0 --no-editable /path/to/project

NOTES:
    - Uses pipx to install directly from your local source
    - Editable installs reflect your source code changes immediately
    - Regular installs are isolated snapshots
    - Each installation gets its own virtual environment
    - All claude-mpm commands will be available in the target directory
    - Auto-detects claude-mpm source directory or use --source to specify

EOF
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -f|--force)
            FORCE=true
            shift
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        --no-editable)
            EDITABLE=false
            shift
            ;;
        -s|--source)
            SOURCE_DIR="$2"
            shift 2
            ;;
        -h|--help)
            show_usage
            exit 0
            ;;
        -*)
            print_error "Unknown option: $1"
            show_usage
            exit 1
            ;;
        *)
            if [[ -z "$INSTALL_DIR" ]]; then
                INSTALL_DIR="$1"
            else
                print_error "Multiple install directories specified"
                show_usage
                exit 1
            fi
            shift
            ;;
    esac
done

# Determine source directory
if [[ -n "$SOURCE_DIR" ]]; then
    # Use specified source directory
    PROJECT_ROOT="$(cd "$SOURCE_DIR" 2>/dev/null && pwd)" || {
        print_error "Source directory does not exist: $SOURCE_DIR"
        exit 1
    }
else
    # Try to auto-detect claude-mpm source directory
    if [[ -f "$PROJECT_ROOT/pyproject.toml" ]]; then
        # Script is in claude-mpm project, use that
        :
    elif [[ -f "pyproject.toml" ]] && grep -q "name.*claude-mpm" pyproject.toml 2>/dev/null; then
        # Current directory is claude-mpm project
        PROJECT_ROOT="$(pwd)"
    else
        # Try to find claude-mpm in common locations
        SEARCH_PATHS=(
            "$HOME/Projects/claude-mpm"
            "$HOME/claude-mpm"
            "$HOME/src/claude-mpm"
            "$HOME/dev/claude-mpm"
        )

        for path in "${SEARCH_PATHS[@]}"; do
            if [[ -f "$path/pyproject.toml" ]] && grep -q "name.*claude-mpm" "$path/pyproject.toml" 2>/dev/null; then
                PROJECT_ROOT="$path"
                break
            fi
        done

        if [[ ! -f "$PROJECT_ROOT/pyproject.toml" ]]; then
            print_error "Could not find claude-mpm source directory."
            print_error "Please specify with --source /path/to/claude-mpm"
            exit 1
        fi
    fi
fi

# Convert relative install path to absolute
if [[ -n "$INSTALL_DIR" && "$INSTALL_DIR" != "." ]]; then
    INSTALL_DIR="$(cd "$INSTALL_DIR" 2>/dev/null && pwd)" || {
        print_error "Install directory does not exist: $INSTALL_DIR"
        exit 1
    }
elif [[ "$INSTALL_DIR" == "." ]]; then
    INSTALL_DIR="$(pwd)"
fi

print_info "Claude MPM Local Pipx Installer"
print_info "Source directory: $PROJECT_ROOT"

# Verify we found the right directory
if [[ ! -f "$PROJECT_ROOT/pyproject.toml" ]]; then
    print_error "pyproject.toml not found in: $PROJECT_ROOT"
    print_error "Please specify correct source with --source /path/to/claude-mpm"
    exit 1
fi

if ! grep -q "name.*claude-mpm" "$PROJECT_ROOT/pyproject.toml" 2>/dev/null; then
    print_error "This doesn't appear to be the claude-mpm project: $PROJECT_ROOT"
    print_error "Please specify correct source with --source /path/to/claude-mpm"
    exit 1
fi

# Check if pipx is available
if ! command -v pipx &> /dev/null; then
    print_error "pipx is not installed. Please install it first:"
    echo "  brew install pipx"
    echo "  # or"
    echo "  pip install pipx"
    exit 1
fi

# Get current version for display
VERSION=$(cat "$PROJECT_ROOT/VERSION" 2>/dev/null || echo "unknown")
BUILD_NUMBER=$(cat "$PROJECT_ROOT/BUILD_NUMBER" 2>/dev/null || echo "0")

if [[ "$EDITABLE" == "true" ]]; then
    print_info "Installing claude-mpm v$VERSION-build.$BUILD_NUMBER (editable)"
else
    print_info "Installing claude-mpm v$VERSION-build.$BUILD_NUMBER (regular)"
fi

# Prepare pipx environment variables and install command
PIPX_ARGS=()

if [[ "$FORCE" == "true" ]]; then
    PIPX_ARGS+=(--force)
fi

if [[ "$EDITABLE" == "true" ]]; then
    PIPX_ARGS+=(--editable)
fi

if [[ -n "$INSTALL_DIR" ]]; then
    PIPX_HOME="$INSTALL_DIR/.pipx"
    PIPX_BIN_DIR="$INSTALL_DIR/.pipx/bin"

    print_info "Installing to: $INSTALL_DIR"
    print_info "Pipx home: $PIPX_HOME"
    print_info "Binaries: $PIPX_BIN_DIR"

    # Create directories
    mkdir -p "$PIPX_BIN_DIR"

    # Set environment variables for pipx
    export PIPX_HOME
    export PIPX_BIN_DIR
else
    print_info "Installing to default pipx location"
fi

# Install with pipx
print_info "Installing claude-mpm..."

if [[ "$VERBOSE" == "true" ]]; then
    pipx install "${PIPX_ARGS[@]}" "$PROJECT_ROOT"
else
    pipx install "${PIPX_ARGS[@]}" "$PROJECT_ROOT" > /dev/null 2>&1
fi

# Verify installation
if [[ -n "$INSTALL_DIR" ]]; then
    CLAUDE_MPM_BIN="$PIPX_BIN_DIR/claude-mpm"
else
    CLAUDE_MPM_BIN="claude-mpm"
fi

if [[ -f "$CLAUDE_MPM_BIN" ]] || command -v "$CLAUDE_MPM_BIN" &> /dev/null; then
    print_success "Installation completed successfully!"

    # Show version
    if [[ -n "$INSTALL_DIR" ]]; then
        VERSION_OUTPUT=$("$CLAUDE_MPM_BIN" --version 2>/dev/null || echo "Version check failed")
        print_info "Installed version: $VERSION_OUTPUT"
        print_info "Binary location: $CLAUDE_MPM_BIN"

        # Show usage instructions
        echo
        print_info "To use this installation:"
        echo "  $CLAUDE_MPM_BIN --help"
        echo
        print_info "To add to PATH for this session:"
        echo "  export PATH=\"$PIPX_BIN_DIR:\$PATH\""
        echo
        print_info "To add to PATH permanently, add this to your ~/.zshrc:"
        echo "  export PATH=\"$PIPX_BIN_DIR:\$PATH\""
    else
        print_info "Installed to default pipx location"
        pipx list | grep claude-mpm || true
    fi
else
    print_error "Installation verification failed"
    exit 1
fi

print_success "Done!"
