#!/usr/bin/env bash
set -euo pipefail

# Resolve script dir and repo root
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
ROOT="${PROJECT_ROOT:-$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel 2>/dev/null || pwd)}"

VIEWS_DIR="$ROOT/resources/views"
ART="$ROOT/.mbs_artifacts"
LIST="$ART/blade_files.txt"
DONE="$ART/done.txt"
CACHE_DIR="$ART/cache"
DISC="$ROOT/MBS_BLADE_discovery.md"

mkdir -p "$ART" "$CACHE_DIR"
touch "$DONE"

if [ ! -d "$VIEWS_DIR" ]; then
  echo "No resources/views directory found at $VIEWS_DIR"; exit 1
fi

# Build deterministic list (macOS compatible fallback)
# GNU find (has -printf)
if find "$VIEWS_DIR" -type f -name "*.blade.php" -printf "%P\n" >/dev/null 2>&1; then
  # prune any dir named MBS_old
  find "$VIEWS_DIR" \
    -type d -name "MBS_old" -prune -o \
    -type f -name "*.blade.php" -printf "%P\n" \
  | sort > "$LIST"
else
  # macOS/BSD find fallback (no -printf)
  ( cd "$VIEWS_DIR" && \
    find . \
      -type d -name "MBS_old" -prune -o \
      -type f -name "*.blade.php" -print \
  | sed 's|^\./||' | sort ) > "$LIST"
fi

if [ ! -f "$DISC" ]; then
  cat > "$DISC" <<'MD'
# MBS_BLADE_discovery

A working map of Blade views: purpose, dependencies, routes, forms, contracts, and gaps.

## Summaries
MD
fi

echo "Indexed $(wc -l < "$LIST") Blade files into $LIST"
echo "Progress file: $DONE"
