#!/bin/bash
# Run the Cube Agent
#
# Usage:
#   ./run.sh "prompt"           # Run agent with prompt (CLI mode)
#   ./run.sh --server           # Start API server
#   ./run.sh --status           # Check environment status
#   ./run.sh --docker           # Build and run in Docker
#   ./run.sh --interactive      # Interactive CLI mode

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CUBE_MCP_DIR="$(dirname "$SCRIPT_DIR")"

# Find Python 3.10+ (required by mcp package)
find_python() {
    for py in python3.13 python3.12 python3.11 python3.10; do
        if command -v $py &>/dev/null; then
            echo $(command -v $py)
            return
        fi
    done

    # Check Homebrew paths
    for py in /opt/homebrew/bin/python3.13 /opt/homebrew/bin/python3.12 /opt/homebrew/bin/python3.11 /opt/homebrew/bin/python3.10; do
        if [ -x "$py" ]; then
            echo "$py"
            return
        fi
    done

    # Fall back to python3 if it's 3.10+
    PY_VERSION=$(python3 -c "import sys; print(sys.version_info.minor)" 2>/dev/null)
    if [ "$PY_VERSION" -ge 10 ] 2>/dev/null; then
        echo "python3"
        return
    fi

    echo ""
}

PYTHON=$(find_python)

if [ -z "$PYTHON" ]; then
    echo "Error: Python 3.10+ required but not found"
    echo ""
    echo "Install with:"
    echo "  brew install python@3.13"
    exit 1
fi

# Check if using Bedrock
if [ -f "$SCRIPT_DIR/llm_config.json" ]; then
    PROVIDER=$("$PYTHON" -c "import json; print(json.load(open('$SCRIPT_DIR/llm_config.json')).get('provider', 'anthropic_bedrock'))" 2>/dev/null)
else
    PROVIDER="anthropic_bedrock"
fi

# Setup virtual environment if needed
setup_venv() {
    if [ ! -d "$SCRIPT_DIR/venv" ]; then
        echo "Creating virtual environment with $PYTHON..."
        "$PYTHON" -m venv "$SCRIPT_DIR/venv"

        echo "Installing dependencies..."
        "$SCRIPT_DIR/venv/bin/pip" install --upgrade pip
        "$SCRIPT_DIR/venv/bin/pip" install -r "$SCRIPT_DIR/requirements.txt"

        echo "Installing cube-mcp package..."
        "$SCRIPT_DIR/venv/bin/pip" install -e "$CUBE_MCP_DIR"

        echo ""
        echo "Setup complete!"
        echo ""
    fi
}

# Note: Auth checking is now handled by Python setup module
# This just does a quick sanity check
check_basic_deps() {
    if [ "$PROVIDER" = "anthropic_bedrock" ]; then
        if ! command -v aws &>/dev/null; then
            echo "Warning: AWS CLI not found. Install with: brew install awscli"
        fi
    else
        if [ -z "$ANTHROPIC_API_KEY" ]; then
            echo "Warning: ANTHROPIC_API_KEY not set"
        fi
    fi
}

# Run in Docker
run_docker() {
    echo "Building and starting Cube Agent in Docker..."
    cd "$SCRIPT_DIR"
    docker compose up --build
}

# Start API server
start_server() {
    setup_venv
    check_basic_deps
    echo "Starting Cube Agent API server..."
    echo "API will be available at http://localhost:8000"
    echo "Docs at http://localhost:8000/docs"
    echo ""
    cd "$SCRIPT_DIR"
    "$SCRIPT_DIR/venv/bin/uvicorn" app.main:app --host 0.0.0.0 --port 8000 --reload
}

# Run CLI mode
run_cli() {
    setup_venv
    check_basic_deps
    cd "$SCRIPT_DIR"
    "$SCRIPT_DIR/venv/bin/python" cube_agent.py "$@"
}

# Main
case "${1:-}" in
    --docker)
        run_docker
        ;;
    --server)
        start_server
        ;;
    --status|-s)
        setup_venv
        "$SCRIPT_DIR/venv/bin/python" cube_agent.py --status
        ;;
    --interactive|-i)
        run_cli --interactive
        ;;
    --setup)
        setup_venv
        cd "$SCRIPT_DIR"
        "$SCRIPT_DIR/venv/bin/python" cube_agent.py --setup
        ;;
    --help|-h)
        echo "Cube Agent"
        echo ""
        echo "Usage:"
        echo "  ./run.sh \"prompt\"        Run agent with prompt"
        echo "  ./run.sh --setup         Run interactive setup wizard"
        echo "  ./run.sh --interactive   Interactive CLI mode"
        echo "  ./run.sh --server        Start API server (http://localhost:8000)"
        echo "  ./run.sh --docker        Build and run in Docker"
        echo "  ./run.sh --status        Check environment status"
        echo "  ./run.sh --sessions      List saved sessions"
        echo ""
        echo "First time? Run: ./run.sh --setup"
        echo ""
        ;;
    *)
        if [ -n "$1" ]; then
            run_cli "$@"
        else
            run_cli
        fi
        ;;
esac
