#!/usr/bin/env bash
# Walk up from CWD to find the highest directory containing CLAUDE.md.
# Usage:
#   eval "$(scripts/find-project-root)"   # sets CLAUDE_PROJECT_ROOT
#   export CLAUDE_PROJECT_ROOT="$(scripts/find-project-root --print)"
#
# With --print: outputs just the path (for subshell capture).
# Without flags: outputs an export statement (for eval).

set -euo pipefail

root=""
dir="$(pwd)"
while [[ "$dir" != "/" ]]; do
    if [[ -f "$dir/CLAUDE.md" ]]; then
        root="$dir"
    fi
    dir="$(dirname "$dir")"
done

if [[ -z "$root" ]]; then
    echo "ERROR: No CLAUDE.md found in any parent directory of $(pwd)" >&2
    exit 1
fi

if [[ "${1:-}" == "--print" ]]; then
    echo "$root"
else
    echo "export CLAUDE_PROJECT_ROOT=\"$root\""
fi
