#!/usr/bin/env bash
# Project-level claude-mpm wrapper that delegates to the scripts directory version

set -e

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

# Prevent infinite recursion by checking if we're already being called from ourselves
if [ -n "$CLAUDE_MPM_WRAPPER_ACTIVE" ]; then
    echo "Error: Recursive call detected. Please check your installation."
    echo "This usually happens when the global 'claude-mpm' command points back to this wrapper."
    echo "Try using the full path: $SCRIPT_DIR/scripts/claude-mpm"
    exit 1
fi

# Mark that we're in the wrapper to prevent recursion
export CLAUDE_MPM_WRAPPER_ACTIVE=1

# Check if running from source or installed
if [ -f "$SCRIPT_DIR/scripts/claude-mpm" ]; then
    # Running from source directory
    exec "$SCRIPT_DIR/scripts/claude-mpm" "$@"
elif command -v claude-mpm &> /dev/null; then
    # Check if the found claude-mpm is actually this script (via symlink)
    FOUND_CLAUDE_MPM=$(command -v claude-mpm)
    RESOLVED_CLAUDE_MPM=$(readlink -f "$FOUND_CLAUDE_MPM" 2>/dev/null || echo "$FOUND_CLAUDE_MPM")
    THIS_SCRIPT=$(readlink -f "$0" 2>/dev/null || echo "$0")

    if [ "$RESOLVED_CLAUDE_MPM" = "$THIS_SCRIPT" ]; then
        # The found claude-mpm is actually this script, use the scripts version
        if [ -f "$SCRIPT_DIR/scripts/claude-mpm" ]; then
            exec "$SCRIPT_DIR/scripts/claude-mpm" "$@"
        else
            echo "Error: scripts/claude-mpm not found in $SCRIPT_DIR"
            exit 1
        fi
    else
        # Running a different installed version
        exec claude-mpm "$@"
    fi
else
    echo "Error: claude-mpm not found. Please run ./install.sh"
    exit 1
fi
