#!/bin/bash
set -e

# install uv
echo "Installing uv..."
curl -LsSf https://astral.sh/uv/install.sh | sh

# add uv to PATH in .bashrc if not already present
echo "Updating PATH in .bashrc..."
if ! grep -q '.local/bin' ~/.bashrc; then
    echo "" >> ~/.bashrc
    echo "# added by CS307 setup script" >> ~/.bashrc
    echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
    echo "added ~/.local/bin to PATH in .bashrc"
fi

# source the uv path to make it available in this script
export PATH="$HOME/.local/bin:$PATH"

# install quarto if not already installed
if command -v quarto &> /dev/null; then
    echo "Quarto is already installed, skipping..."
else
    echo "Installing Quarto..."
    wget https://github.com/quarto-dev/quarto-cli/releases/download/v1.8.25/quarto-1.8.25-linux-amd64.tar.gz
    mkdir -p ~/opt
    tar -C ~/opt -xzf quarto-1.8.25-linux-amd64.tar.gz
    mkdir -p ~/.local/bin
    ln -sf ~/opt/quarto-1.8.25/bin/quarto ~/.local/bin/quarto
    rm quarto-1.8.25-linux-amd64.tar.gz
fi

# install vscode extensions
echo "Installing VSCode extensions..."
code-server --install-extension ms-python.python
code-server --install-extension ms-toolsai.jupyter
code-server --install-extension quarto.quarto

# create and setup cs307 folder
echo "Setting up CS 307 course folder..."
mkdir -p ~/cs307
cd ~/cs307

# get course pyproject.toml
echo "Downloading CS 307 requirements file..."
wget -O pyproject.toml https://cs307.org/requirements/pyproject.toml

# get the lab template
echo "Downloading CS 307 lab template notebook..."
wget -O lab-template.ipynb https://cs307.org/policy/template/lab-template.ipynb

# create virtual environment if needed
if uv sync --dry-run 2>&1 | grep -q "Audited"; then
    echo "Python environment is already up to date."
else
    echo "Creating Python virtual environment and installing dependencies..."
    uv sync --compile-bytecode
fi

# configure VSCode settings
echo "Configuring VSCode settings..."
mkdir -p .vscode
cat > .vscode/settings.json << 'EOF'
{
    "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python",
    "terminal.integrated.cwd": "${workspaceFolder}",
    "jupyter.kernels.excludePythonEnvironments": [
        "opt/conda/bin/python",
        "/bin/python3",
        "/usr/bin/python3"
    ]
}
EOF

# activate the virtual environment
echo "Activating virtual environment..."
source .venv/bin/activate

# wrap-up messaging
echo ""
echo "✓ Setup complete!"
echo ""
echo "Be sure open the cs307 folder in VSCode before continuing!"
echo ""
