#!/bin/bash
set -e

echo "--- [ENTRYPOINT] Starting environment setup ---"

cd /repo
if [ -z "${GITHUB_REPO_URL:-}" ]; then echo "GITHUB_REPO_URL is required"; exit 1; fi

# Optional: run system packages installation if provided (allowlisted by BE)
if [ -n "${SYSTEM_PACKAGES:-}" ]; then
    echo "Installing system packages: ${SYSTEM_PACKAGES}"
    sudo apt-get update && sudo apt-get install -y --no-install-recommends ${SYSTEM_PACKAGES} || true
fi

echo "Cloning ${GITHUB_REPO_URL} to inspect for dependencies..."
git clone "${GITHUB_REPO_URL}" .

echo "Detecting package manager..."
if [ -f "poetry.lock" ]; then
    echo "Poetry project detected. Installing dependencies with 'poetry install'."
    poetry install --with dev || poetry install
    export VENV_PATH=$(poetry env info --path)
elif [ -f "pyproject.toml" ] && grep -q "\[tool.uv\]" "pyproject.toml"; then
    echo "UV project detected. Installing dependencies with 'uv sync'."
    uv venv
    uv sync --all-extras || uv sync
    export VENV_PATH=$(pwd)/.venv
elif [ -f "requirements.txt" ]; then
    echo "requirements.txt detected. Installing with pip."
    python -m venv .venv
    source .venv/bin/activate
    pip install -r requirements.txt || true
    [ -f "requirements-test.txt" ] && pip install -r requirements-test.txt || true
    [ -f "requirements-dev.txt" ] && pip install -r requirements-dev.txt || true
    export VENV_PATH=$(pwd)/.venv
else
    echo "WARNING: No standard dependency file found. Proceeding without installation."
    python -m venv .venv
    export VENV_PATH=$(pwd)/.venv
fi

# Optional: LLM-provided pre/install/post commands (allowlisted and sanitized by BE)
run_cmds_if_any() {
    CMDS_VAR="$1"
    CMDS_VAL="${!CMDS_VAR}"
    if [ -n "$CMDS_VAL" ]; then
        echo "Running commands from $CMDS_VAR"
        /bin/bash -lc "$CMDS_VAL" || true
    fi
}

run_cmds_if_any PRE_INSTALL_CMDS
run_cmds_if_any INSTALL_CMDS
run_cmds_if_any POST_INSTALL_CMDS

echo "--- [ENTRYPOINT] Handing off to optimization script ---"
rm -rf /repo/*
/app/scripts/run_optimization.sh


