#!/usr/bin/env bash
# Claude MPM Development Launcher
# Usage: ./claude-mpm-dev [args]
#        ./claude-mpm-dev --debug [args]  (verbose mode)

set -e

# Get project root (where this script is located)
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_ROOT="$SCRIPT_DIR"
VENV_DIR="$PROJECT_ROOT/venv"
SRC_DIR="$PROJECT_ROOT/src"

# Check for debug/verbose flag
VERBOSE=false
for arg in "$@"; do
    if [[ "$arg" == "--debug" ]] || [[ "$arg" == "-d" ]] || [[ "$arg" == "--verbose" ]]; then
        VERBOSE=true
        break
    fi
done

# Helper functions
print_info() {
    if [[ "$VERBOSE" == true ]]; then
        echo "[DEV] $1" >&2
    fi
}

print_error() {
    echo "[ERROR] $1" >&2
}

# Create venv if missing
if [ ! -d "$VENV_DIR" ]; then
    echo "[DEV] Creating virtual environment..." >&2
    python3 -m venv "$VENV_DIR" || {
        print_error "Failed to create virtual environment"
        exit 1
    }
fi

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

# Check if dependencies installed
if ! python -c "import click" 2>/dev/null; then
    echo "[DEV] Installing dependencies..." >&2
    pip install --upgrade pip > /dev/null 2>&1
    pip install -e "$PROJECT_ROOT[dev]" > /dev/null 2>&1 || {
        print_error "Failed to install dependencies"
        exit 1
    }
fi

# Set environment
export PYTHONPATH="$SRC_DIR:$PYTHONPATH"
export DISABLE_TELEMETRY=1
export CLAUDE_MPM_USER_PWD="$(pwd)"

# Debug info
if [[ "$VERBOSE" == true ]]; then
    print_info "Working directory: $(pwd)"
    print_info "Project root: $PROJECT_ROOT"
    print_info "Python path: $SRC_DIR"
    print_info "Running: python -m claude_mpm $*"
fi

# Launch Claude MPM from source
cd "$PROJECT_ROOT"
exec python -m claude_mpm "$@"
