#!/usr/bin/env bash
# Idempotent AGENTS.md bootstrap (Task 486).
#
# Usage: agents-md-bootstrap.sh <account_dir>
#
# Walks <account_dir>/specialists/agents/ for every core specialist .md
# (filename without `--`), parses YAML frontmatter, and ensures
# <account_dir>/agents/admin/AGENTS.md contains exactly one line of the form
# `- **specialists:<name>**: <description>`. Existing lines whose prefix
# matches `^- **specialists:<name>**:` are preserved verbatim (operator-tuned
# lines never get clobbered); missing entries are appended.
#
# Emits one stdout observability line, two-space indented to match the
# surrounding setup-account.sh log style:
#   "  [admin-bootstrap] AGENTS.md specialists=<n> appended=<m> existing=<k>"
#
# Names must follow the `[a-z][a-z0-9-]*` convention so direct interpolation
# in the regex matcher is safe.

set -euo pipefail

ACCOUNT_DIR="${1:?Usage: agents-md-bootstrap.sh <account_dir>}"
AGENTS_MD="$ACCOUNT_DIR/agents/admin/AGENTS.md"

mkdir -p "$(dirname "$AGENTS_MD")"
if [ ! -f "$AGENTS_MD" ]; then
  printf '# Installed Roles\n\nDispatch via the Agent tool with `subagent_type: "specialists:{name}"`.\n\n' > "$AGENTS_MD"
fi

_specialists=0
_appended=0
_existing=0
for specialist in "$ACCOUNT_DIR/specialists/agents/"*.md; do
  [ -f "$specialist" ] || continue
  case "$(basename "$specialist")" in
    *--*) continue ;;  # Premium plugin agent — out of scope for the bootstrap.
  esac
  _name=$(sed -n 's/^name: *//p' "$specialist" | head -1)
  _desc=$(sed -n 's/^description: *"*//p' "$specialist" | sed 's/"$//' | head -1)
  [ -z "$_name" ] && continue
  _specialists=$((_specialists + 1))
  if grep -qE "^- \*\*specialists:${_name}\*\*:" "$AGENTS_MD"; then
    _existing=$((_existing + 1))
    continue
  fi
  printf -- '- **specialists:%s**: %s\n' "$_name" "$_desc" >> "$AGENTS_MD"
  _appended=$((_appended + 1))
done
echo "  [admin-bootstrap] AGENTS.md specialists=$_specialists appended=$_appended existing=$_existing"
