#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# Prepare a development clone: create the virtual environment, install the
# development dependencies, and point Git at the tracked hooks.

set -eu

SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
PROJECT_ROOT=$(dirname -- "$SCRIPT_DIR")

cd "$PROJECT_ROOT"

if command -v python3 >/dev/null 2>&1; then
    PYTHON=$(command -v python3)
else
    printf '%s\n' "error: python3 is required" >&2
    exit 127
fi

if [ ! -x "$PROJECT_ROOT/.venv/bin/python" ]; then
    printf '%s\n' "Creating .venv..."
    "$PYTHON" -m venv "$PROJECT_ROOT/.venv"
fi

printf '%s\n' "Installing development dependencies..."
"$PROJECT_ROOT/.venv/bin/python" -m pip install -r "$PROJECT_ROOT/requirements-dev.txt"

printf '%s\n' "Configuring Git hooks..."
git -C "$PROJECT_ROOT" config core.hooksPath scripts/hooks

# The trusted-side gates shell out to host tools: check-docs needs lychee,
# pymarkdown and rg on PATH, and the oracle grades a snapshot that excludes
# .venv by design (it uses the host's installed toolchain). A missing tool
# does not block code-only work, but it will red those gates — name it here
# so the next host does not discover it by battery failure.
missing=""
for tool in git rg lychee pymarkdown; do
    command -v "$tool" >/dev/null 2>&1 || missing="$missing $tool"
done
if [ -n "$missing" ]; then
    printf '%s\n' "warning: host tools missing from PATH:$missing" >&2
    printf '%s\n' "  rg:         apt install ripgrep" >&2
    printf '%s\n' "  lychee:     https://github.com/lycheeverse/lychee/releases (place on PATH)" >&2
    printf '%s\n' "  pymarkdown: pipx install pymarkdownlnt (or symlink it onto PATH)" >&2
    printf '%s\n' "  The docs gate and the trusted-side oracle gate need them." >&2
fi

printf '%s\n' "Development environment ready."
