#!/bin/bash
#
# Project bootstrap script - Sets up Python development environment for agent-cost-estimator
#
# This script MUST be sourced to properly set up the environment:
#   source bootstrap
#
# Windows (PowerShell): dot-source bootstrap.ps1 instead
#   . .\bootstrap.ps1 [--env name] [--python 3.x.x] [-c|--clean] [--no-env] [--local]
#
# What it does:
# 1. Installs pyenv and required system dependencies if needed
# 2. Initializes pyenv and pyenv-virtualenv in the current shell
# 3. Creates a Python virtual environment named 'venv' (or custom name)
# 4. Activates the virtual environment
# 5. Installs the project in development mode with all dependencies
#
# Options:
#   --pyenv        Force reinstall pyenv
#   -c, --clean    Delete existing environment before creating a new one
#   --env NAME     Use a custom environment name (default: venv)
#   --python VER   Use a specific Python version (default: 3.11.8)
#   --no-env      Skip virtual environment creation, install to current Python
#   --local       Install package with --user flag (user-local installation)
#
# Usage:
#   source bootstrap [--pyenv] [-c|--clean] [--env custom_name] [--python 3.x.x] [--no-env] [--local]
#      ex. source bootstrap --pyenv -c --env my_env --python 3.11.8
#      ex. source bootstrap --no-env --local

# =============================================
# VARIABLES
# =============================================
PYTHON_VERSION="3.11.8"  # Default Python version - change as needed
export PYENV_NAME="venv"   # Default environment name
FORCE_PYENV_INSTALL=false # Flag to force pyenv reinstallation
CLEAN_ENVIRONMENT=false   # Flag to delete and recreate environment
NO_ENVIRONMENT=false      # Flag to skip virtual environment creation
LOCAL_INSTALL=false       # Flag to install with --user
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"  # Scripts root directory

# =============================================
# UTILITY FUNCTIONS
# =============================================

echo_status() {
    echo "[BOOTSTRAP] $1"
}

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

echo_warning() {
    echo "[WARNING] $1" >&2
}

# =============================================
# FUNCTION DEFINITIONS
# =============================================

check_python_installed() {
    # First check if Python is installed at all
    if ! command -v python &> /dev/null && ! command -v python3 &> /dev/null; then
        echo_error "Python is not installed. Please install Python $PYTHON_VERSION before running this script."
        echo_error "On Ubuntu/Debian: sudo apt-get install python3"
        echo_error "On macOS: brew install python@$PYTHON_VERSION"
        echo_error "Or download from: https://www.python.org/downloads/"
        return 1
    fi

    # If pyenv is available and we're using an environment, check if the specific version is installed
    if [ "$NO_ENVIRONMENT" = false ] && command -v pyenv &> /dev/null; then
        if ! pyenv versions | grep -q "$PYTHON_VERSION"; then
            echo_status "Python $PYTHON_VERSION is not available in pyenv. Installing it now..."
            if ! pyenv install "$PYTHON_VERSION"; then
                echo_error "Failed to install Python $PYTHON_VERSION via pyenv"
                echo_error "You may need to install build dependencies first or install it manually"
                return 1
            fi
        fi
    fi

    return 0
}

initialize_pyenv() {
    # Skip if we're not using an environment
    if [ "$NO_ENVIRONMENT" = true ]; then
        echo_status "Skipping pyenv initialization (--no-env mode)"
        return 0
    fi

    # Set up pyenv environment variables
    export PYENV_ROOT="$HOME/.pyenv"
    export PATH="$PYENV_ROOT/bin:$PATH"

    # Check if pyenv is already properly initialized
    if command -v pyenv &> /dev/null && pyenv virtualenvs &> /dev/null; then
        echo_status "pyenv is already properly initialized"
        return 0
    fi

    # Check if pyenv exists
    if [ ! -f "$PYENV_ROOT/bin/pyenv" ]; then
        echo_error "pyenv not found at $PYENV_ROOT/bin/pyenv"
        echo_error "Please install pyenv first or use --pyenv flag"
        return 1
    fi

    echo_status "Initializing pyenv..."

    # Clear any existing pyenv functions to avoid conflicts
    if declare -F | grep -q 'pyenv$'; then
        unset -f pyenv
    fi

    # Initialize pyenv and pyenv-virtualenv
    eval "$("$PYENV_ROOT/bin/pyenv" init -)" || {
        echo_error "Failed to initialize pyenv"
        return 1
    }

    # Only init virtualenv plugin if available
    if [ -f "$PYENV_ROOT/plugins/pyenv-virtualenv/bin/pyenv-virtualenv-init" ]; then
        eval "$("$PYENV_ROOT/bin/pyenv" virtualenv-init -)" || {
            echo_warning "Failed to initialize pyenv-virtualenv plugin"
        }
    fi

    # Verify initialization
    if ! pyenv virtualenvs &> /dev/null; then
        echo_error "Failed to initialize pyenv"
        return 1
    fi

    echo_status "pyenv initialized successfully"
    return 0
}

install_pyenv_dependencies() {
    # Install pyenv dependencies on Debian-based systems
    if [ -f /etc/debian_version ] || [ -f /etc/os-release ] && grep -q "ID=debian\|ID=ubuntu" /etc/os-release 2>/dev/null; then
        echo_status "Installing pyenv dependencies..."
        if ! command -v sudo &> /dev/null; then
            echo_error "sudo is required to install dependencies"
            return 1
        fi
        sudo apt-get update && sudo apt-get install -y \
            make build-essential libssl-dev zlib1g-dev \
            libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
            libncurses-dev xz-utils tk-dev libffi-dev liblzma-dev \
            python3-openssl git || {
            echo_error "Failed to install pyenv dependencies"
            echo_warning "You may need to install them manually"
            return 1
        }
    elif [ "$(unname)" = "Darwin" ]; then
        echo_status "Detected macOS - ensuring required tools are available"
        if ! command -v brew &> /dev/null; then
            echo_warning "Homebrew (brew) not found. You may need to install pyenv dependencies manually."
            echo_warning "Recommended: brew install pyenv"
            return 0
        fi
        if ! brew list pyenv &> /dev/null; then
            echo_status "Installing pyenv via homebrew..."
            brew install pyenv || {
                echo_error "Failed to install pyenv via homebrew"
                return 1
            }
        fi
    fi
    return 0
}

install_pyenv() {
    echo_status "Installing pyenv..."
    curl -fsSL https://pyenv.run | bash || {
        echo_error "Failed to install pyenv"
        return 1
    }
    return 0
}

check_and_install_pyenv() {
    # Skip if we're not using an environment
    if [ "$NO_ENVIRONMENT" = true ]; then
        return 0
    fi

    # Check if pyenv is already available
    if command -v pyenv &> /dev/null && [ "$FORCE_PYENV_INSTALL" = false ]; then
        echo_status "pyenv is already available"
        return 0
    fi

    # Handle existing pyenv directory
    if [ -d "$HOME/.pyenv" ]; then
        if [ "$FORCE_PYENV_INSTALL" = true ]; then
            echo_status "Removing existing pyenv installation..."
            rm -rf "$HOME/.pyenv" || {
                echo_error "Failed to remove existing pyenv installation"
                return 1
            }
        else
            echo_status "Found existing pyenv directory"
        fi
    fi

    # Install dependencies first
    install_pyenv_dependencies || return 1

    # Install pyenv
    install_pyenv || return 1

    # Source the pyenv setup in current shell
    export PYENV_ROOT="$HOME/.pyenv"
    export PATH="$PYENV_ROOT/bin:$PATH"
    eval "$("$PYENV_ROOT/bin/pyenv" init -)"

    return 0
}

clean_environment() {
    if [ "$NO_ENVIRONMENT" = true ]; then
        return 0
    fi

    if pyenv virtualenvs | grep -q "$PYENV_NAME"; then
        echo_status "Deleting existing virtual environment $PYENV_NAME..."
        pyenv uninstall -f "$PYENV_NAME" >/dev/null 2>&1 || {
            echo_error "Failed to delete virtual environment $PYENV_NAME"
            return 1
        }
    else
        echo_status "Virtual environment $PYENV_NAME does not exist, skipping deletion"
    fi
    return 0
}

install_python_version() {
    local version="$1"
    echo_status "Installing Python $version using pyenv..."
    pyenv install "$version" || {
        echo_error "Failed to install Python $version"
        return 1
    }
    return 0
}

check_environment_exists() {
    # Skip if we're not using an environment
    if [ "$NO_ENVIRONMENT" = true ]; then
        return 0
    fi

    # Clean if requested
    if [ "$CLEAN_ENVIRONMENT" = true ]; then
        clean_environment || return 1
    fi

    # Check if Python version is available
    if ! pyenv versions | grep -q "$PYTHON_VERSION"; then
        install_python_version "$PYTHON_VERSION" || return 1
    fi

    # Create environment if it doesn't exist
    if ! pyenv virtualenvs --bare 2>/dev/null | grep -qx "$PYENV_NAME"; then
        echo_status "Creating virtual environment $PYENV_NAME..."
        pyenv virtualenv "$PYTHON_VERSION" "$PYENV_NAME" || {
            echo_error "Failed to create virtual environment $PYENV_NAME"
            return 1
        }
    else
        echo_status "Virtual environment $PYENV_NAME already exists"
    fi

    return 0
}

activate_environment() {
    # Skip if we're not using an environment
    if [ "$NO_ENVIRONMENT" = true ]; then
        echo_status "Skipping environment activation (--no-env mode)"
        return 0
    fi

    echo_status "Activating $PYENV_NAME..."

    # Try pyenv activate first
    if command -v pyenv &> /dev/null; then
        # Get the virtualenv path
        local venv_path
        venv_path=$(pyenv prefix "$PYENV_NAME" 2>/dev/null)
        
        if [ -n "$venv_path" ] && [ -d "$venv_path" ]; then
            # Manually activate by sourcing the activate script
            local activate_script="$venv_path/bin/activate"
            if [ -f "$activate_script" ]; then
                source "$activate_script" || {
                    echo_error "Failed to source activation script: $activate_script"
                    return 1
                }
                echo_status "Successfully activated $PYENV_NAME"
                return 0
            fi
        fi
        
        # Fallback: try pyenv activate
        if pyenv activate "$PYENV_NAME" 2>/dev/null; then
            echo_status "Successfully activated $PYENV_NAME with pyenv"
            return 0
        fi
    fi

    # Last resort: check common virtualenv locations
    local possible_paths=(
        "$HOME/.pyenv/versions/$PYENV_NAME/bin/activate"
        "$HOME/.virtualenvs/$PYENV_NAME/bin/activate"
        "$SCRIPT_DIR/venv/bin/activate"
        "$SCRIPT_DIR/.venv/bin/activate"
    )

    for path in "${possible_paths[@]}"; do
        if [ -f "$path" ]; then
            source "$path" || {
                echo_error "Failed to source activation script: $path"
                return 1
            }
            echo_status "Successfully activated $PYENV_NAME"
            return 0
        fi
    done

    echo_error "Failed to activate $PYENV_NAME - could not find activation script"
    return 1
}

install_requirements() {
    echo_status "Installing requirements..."

    # Check if pyproject.toml exists in the current directory
    if [ -f "$SCRIPT_DIR/pyproject.toml" ]; then
        echo_status "Installing package in development mode from pyproject.toml..."
        
        # Build the pip install command
        local pip_cmd="pip install -e ."
        
        # Add dev extras if not in --no-env mode
        if [ "$NO_ENVIRONMENT" = false ]; then
            pip_cmd="$pip_cmd[dev]"
        fi
        
        # Add --user flag if --local is specified
        if [ "$LOCAL_INSTALL" = true ]; then
            pip_cmd="$pip_cmd --user"
        fi
        
        # Add --break-system-packages for safety
        pip_cmd="$pip_cmd --break-system-packages"
        
        (cd "$SCRIPT_DIR" && eval "$pip_cmd") || {
            echo_error "Failed to install package and dependencies from pyproject.toml"
            return 1
        }
    else
        echo_error "No pyproject.toml found in $SCRIPT_DIR"
        return 1
    fi
    
    return 0
}

upgrade_pip() {
    echo_status "Upgrading pip..."
    python -m pip install --upgrade pip --break-system-packages || {
        echo_warning "Failed to upgrade pip"
        echo_warning "Continuing with requirements installation..."
    }
}

# =============================================
# PARSE COMMAND LINE ARGUMENTS
# =============================================

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        --pyenv)
            FORCE_PYENV_INSTALL=true
            shift
            ;;
        -c|--clean)
            CLEAN_ENVIRONMENT=true
            shift
            ;;
        --env)
            if [ -n "$2" ]; then
                PYENV_NAME="$2"
                shift 2
            else
                echo_error "--env requires an environment name argument"
                return 1
            fi
            ;;
        --python)
            if [ -n "$2" ]; then
                PYTHON_VERSION="$2"
                shift 2
            else
                echo_error "--python requires a version number argument"
                return 1
            fi
            ;;
        --no-env)
            NO_ENVIRONMENT=true
            shift
            ;;
        --local)
            LOCAL_INSTALL=true
            shift
            ;;
        *)
            echo_error "Unknown option: $1"
            echo "Usage: source bootstrap [--pyenv] [-c|--clean] [--env custom_name] [--python 3.x.x] [--no-env] [--local]"
            return 1
            ;;
    esac
done

# Export the environment name for use throughout the script
export PYENV_NAME

# =============================================
# MAIN EXECUTION
# =============================================
echo_status "Starting agent-cost-estimator bootstrap with environment: $PYENV_NAME"

if [ "$FORCE_PYENV_INSTALL" = true ]; then
    echo_status "Forcing pyenv reinstallation"
fi

if [ "$NO_ENVIRONMENT" = true ]; then
    echo_status "Running in --no-env mode (no virtual environment will be created)"
fi

if [ "$LOCAL_INSTALL" = true ]; then
    echo_status "Running in --local mode (will install with --user flag)"
fi

# 1. Check if Python is installed
if ! check_python_installed; then
    return 1
fi

# 2. Check/install pyenv (skip if --no-env)
if [ "$NO_ENVIRONMENT" = false ]; then
    if ! check_and_install_pyenv; then
        return 1
    fi

    # 3. Initialize pyenv (skip if --no-env)
    if ! initialize_pyenv; then
        return 1
    fi

    # 4. Check/create virtual environment (skip if --no-env)
    if ! check_environment_exists; then
        return 1
    fi

    # 5. Activate the environment (skip if --no-env)
    if ! activate_environment; then
        return 1
    fi
else
    echo_status "Using current Python environment (no venv)"
fi

# 6. Upgrade pip
upgrade_pip

# 7. Install requirements (including package in dev mode with all dependencies)
install_requirements

# Final verification
echo_status "Bootstrap completed successfully!"

if [ "$NO_ENVIRONMENT" = false ]; then
    echo_status "Virtual environment '$PYENV_NAME' is active"
else
    echo_status "Using current Python environment"
fi

echo_status "Python: $(python --version) ($(which python))"
echo_status "Pip: $(pip --version)"
echo_status ""
echo_status "To verify installation, try:"
echo_status "  agent-cost-estimator --help"
if [ "$NO_ENVIRONMENT" = false ]; then
    echo_status "  python -m pytest tests/"
fi
echo_status ""
echo_status "Happy coding!"
