#!/bin/bash

# Check if .venv exists
if [[ -d ".venv" ]]; then
     # Activate the virtual environment
     export VIRTUAL_ENV="$PWD/.venv"
     export PATH="$VIRTUAL_ENV/bin:$PATH"

     # Verify we're using the right Python
     if [[ -x "$VIRTUAL_ENV/bin/python3.14" ]]; then
          export PYTHONPATH="$PWD/src:$PYTHONPATH"
          echo "Activated virtual environment: $VIRTUAL_ENV"
     else
          echo "Warning: Virtual environment Python not found"
     fi

else
     echo "Warning: No .venv directory found"
fi

# Run pip to update packages inside the venv
echo "Running pip update..."
"$VIRTUAL_ENV/bin/python3.14" -m pip install --upgrade pip
# "$VIRTUAL_ENV/bin/python3.14" -m pip install --no-cache-dir --upgrade $(pip list --format=freeze | grep -v '^\-e' | grep -v '^griffe==' | cut -d = -f 1 | tr '\n' ' ') # Exclude the griffe package for now
"$VIRTUAL_ENV/bin/python3.14" -m pip install --no-cache-dir --upgrade $(pip list --format=freeze | grep -v '^\-e' | cut -d = -f 1 | tr '\n' ' ')
# "$VIRTUAL_ENV/bin/python3.14" -m pip freeze > requirements.txt

# Update requirements.txt with pinned versions only if installs succeeded
if [[ $? -eq 0 ]]; then
  "$VIRTUAL_ENV/bin/python3.14" -m pip freeze > requirements.txt
  echo "Packages updated successfully"
else
  echo "pip install failed; requirements.txt not updated"
fi

# Sync Vale
vale sync

echo "Environment configured with direnv"
