#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "$0")/../.." && pwd)"
DOCS_DIR="$ROOT_DIR/docs"
mkdir -p "$DOCS_DIR/site/index" "$DOCS_DIR/.generated"
all_files=$(rg --files "$ROOT_DIR" -g "**/*.md" -g '!**/node_modules/**' -g '!**/.worktrees/**' -g '!**/default/**' | sort)
write_bucket(){ local title="$1"; local out="$2"; local pattern="$3"; { echo "# $title"; echo; echo "Autogenerated by docs/scripts/generate-doc-index.sh"; echo; while IFS= read -r f; do rel="${f#${ROOT_DIR}/}"; if [[ "$rel" =~ $pattern ]]; then echo "- [$rel](../${rel})"; fi; done <<< "$all_files"; } > "$out"; }
{ echo '# Raw/All'; echo; echo 'Autogenerated by docs/scripts/generate-doc-index.sh'; echo; while IFS= read -r f; do rel="${f#${ROOT_DIR}/}"; echo "- [$rel](../${rel})"; done <<< "$all_files"; } > "$DOCS_DIR/site/index/raw-all.md"
write_bucket "Planning" "$DOCS_DIR/site/index/planning.md" '(plan|roadmap|wbs|backlog|planning)'
write_bucket "Specs" "$DOCS_DIR/site/index/specs.md" '(spec|prd|adr|requirements)'
write_bucket "Research" "$DOCS_DIR/site/index/research.md" '(research|analysis|spike)'
write_bucket "Worklogs" "$DOCS_DIR/site/index/worklogs.md" '(worklog|session|report|reports)'
write_bucket "Other" "$DOCS_DIR/site/index/other.md" '.*'
printf '{\n  "generated": true,\n  "tool": "docs/scripts/generate-doc-index.sh"\n}\n' > "$DOCS_DIR/.generated/doc-index.json"
