#!/bin/bash
set -e

# This script is used to set up a new developer environment using Poetry.

# Detect project root as the closest directory (max 2 levels up) containing a 'pyproject.toml' file
PROJECT_ROOT=""
for DIR in "." ".." "../.."; do
    if [ -f "$DIR/pyproject.toml" ]; then
        PROJECT_ROOT="$(cd "$DIR" && pwd)"
        break
    fi
done

if [ -z "$PROJECT_ROOT" ]; then
    echo "Error: Could not find project root (no 'pyproject.toml' found within 2 levels up)."
    exit 1
fi

cd "$PROJECT_ROOT"

# Ensure poetry is installed in the venv
if [ ! -x ".venv/bin/poetry" ]; then
    echo "Poetry not found in .venv. Installing Poetry into the virtual environment..."
    source .venv/bin/activate
    pip install poetry
fi

# Check if poetry.lock is out of date and update if necessary
if poetry check --lock 2>&1 | grep -q 'poetry.lock'; then
    echo "poetry.lock is out of date with pyproject.toml. Running 'poetry lock'..."
    poetry lock
else
    echo "poetry.lock is up to date."
fi

# Install all dependencies, including dev and test
echo "Installing all Python dependencies with Poetry (including dev and test)..."
poetry install

# Check .pre-commit-config.yaml exists or raise an error
echo "Checking for .pre-commit-config.yaml..."
if [ ! -f .pre-commit-config.yaml ]; then
    echo "Error: .pre-commit-config.yaml not found. Please ensure it exists in the project root."
    exit 1
fi

# Install pre-commit hooks
echo "Installing pre-commit hooks..."
pre-commit install
