#!/usr/bin/env bash
# Claude MPM executable wrapper with venv management

# Get the directory where this script is located, following symlinks
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
    DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
    SOURCE="$(readlink "$SOURCE")"
    [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
VENV_DIR="$PROJECT_ROOT/venv"
SRC_DIR="$PROJECT_ROOT/src"

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

# Function to print colored output
print_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

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

# Check if virtual environment exists
if [ ! -d "$VENV_DIR" ]; then
    print_info "Creating virtual environment..."
    python3 -m venv "$VENV_DIR"
    
    if [ $? -ne 0 ]; then
        print_error "Failed to create virtual environment"
        exit 1
    fi
fi

# Activate virtual environment
print_info "Activating virtual environment..."
source "$VENV_DIR/bin/activate"

# Check if dependencies are installed
if ! python -c "import click" 2>/dev/null; then
    print_info "Installing dependencies..."
    pip install --upgrade pip > /dev/null 2>&1
    
    # Install in development mode with all dependencies
    pip install -e "$PROJECT_ROOT[dev]" > /dev/null 2>&1
    
    if [ $? -ne 0 ]; then
        print_warning "Some dependencies failed to install, continuing anyway..."
    fi
fi

# Set PYTHONPATH to include src directory
export PYTHONPATH="$SRC_DIR:$PYTHONPATH"

# Enable debug logging if requested
if [[ " $@ " =~ " --debug " ]] || [[ " $@ " =~ " -d " ]]; then
    export CLAUDE_MPM_DEBUG=1
    print_info "Debug mode enabled"
fi

# Preserve the original working directory
export CLAUDE_MPM_USER_PWD="$(pwd)"

# Log the working directory
print_info "Working directory: $(pwd)"
print_info "Framework path: $PROJECT_ROOT"

# Check if this is a claude-mpm specific command or should be passed to claude
MPM_PREFIX="--mpm:"
MPM_COMMANDS=("run" "tickets" "info" "agents" "ui" "memory")
FIRST_ARG="${1:-}"

# Check if first argument is an MPM command (with or without prefix)
IS_MPM_COMMAND=false

# Check for prefixed commands (including --mpm:ui)
if [[ "$FIRST_ARG" == "$MPM_PREFIX"* ]]; then
    IS_MPM_COMMAND=true
    print_info "Detected MPM command: $FIRST_ARG"
fi

# Check for unprefixed commands (legacy support)
for cmd in "${MPM_COMMANDS[@]}"; do
    if [[ "$FIRST_ARG" == "$cmd" ]]; then
        IS_MPM_COMMAND=true
        break
    fi
done

# Check if it's a help/version request for claude-mpm
if [[ "$FIRST_ARG" == "--help" ]] || [[ "$FIRST_ARG" == "-h" ]] || [[ "$FIRST_ARG" == "--version" ]] || [[ "$FIRST_ARG" == "-v" ]] || [[ -z "$FIRST_ARG" ]]; then
    # Show claude-mpm help for these
    IS_MPM_COMMAND=true
fi

# Check if it's a claude-mpm specific flag (with or without prefix)
MPM_FLAGS=("--logging" "--log-dir" "--framework-path" "--agents-dir" "--no-hooks" "--no-tickets" "--subprocess" "--interactive-subprocess" "--todo-hijack" "-i" "--input" "--non-interactive" "--no-native-agents" "-d" "--debug" "--launch-method" "--monitor" "--websocket-port")
for flag in "${MPM_FLAGS[@]}"; do
    if [[ " $* " =~ " $flag " ]] || [[ " $* " =~ " --mpm:${flag#--} " ]] || [[ " $* " =~ " -mpm:${flag#-} " ]]; then
        IS_MPM_COMMAND=true
        break
    fi
done

if [[ "$IS_MPM_COMMAND" == true ]]; then
    # Run claude-mpm
    cd "$PROJECT_ROOT"
    
    # Transform --mpm: prefixed flags to regular flags for Python
    # Special handling for --mpm:ui to keep it as a single argument
    ARGS=()
    for arg in "$@"; do
        if [[ "$arg" == "--mpm:ui" ]]; then
            # Keep --mpm:ui as is for proper subparser handling
            ARGS+=("--mpm:ui")
        elif [[ "$arg" == "--mpm:"* ]]; then
            # Transform other --mpm: prefixed commands
            ARGS+=("--mpm:${arg#--mpm:}")
        elif [[ "$arg" == "-mpm:"* ]]; then
            # Remove -mpm: prefix
            ARGS+=("-${arg#-mpm:}")
        else
            ARGS+=("$arg")
        fi
    done
    
    # Debug: Print the command
    if [[ "$CLAUDE_MPM_DEBUG" == "1" ]]; then
        print_info "Running: python -m claude_mpm ${ARGS[*]}"
    fi
    
    exec python -m claude_mpm "${ARGS[@]}"
else
    # Pass through to claude CLI
    print_info "Passing through to Claude CLI..."
    exec claude --dangerously-skip-permissions "$@"
fi