# account-schema-owned-dirs.sh — merge plugin-declared owned top-level dirs into
# an account's SCHEMA.md, and reconcile every account at install time.
#
# Requires PROJECT_DIR exported by the caller. Sourced by provision-account-dir.sh
# and setup-account.sh.

_ACCT_SCHEMA_LIB_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
_ACCT_SCHEMA_PY="$_ACCT_SCHEMA_LIB_DIR/account-schema-owned-dirs.py"

# merge_owned_dirs_into_schema <account_dir>
# Unions the brand's declared owned dirs into <account_dir>/SCHEMA.md and logs
# the seam. Idempotent.
merge_owned_dirs_into_schema() {
  local _acct="$1"
  local _out
  _out="$(PROJECT_DIR="$PROJECT_DIR" python3 "$_ACCT_SCHEMA_PY" merge "$_acct" 2>/dev/null)"
  echo "  [acct-schema] op=seed-owned-dirs ${_out}"
}

# seed_domain_root_dirs <account_dir>
# mkdir each root domain bucket the brand's vertical projects (Property ->
# properties/ for estate-agent, Job/Customer/... for construction), so the
# operator-data buckets exist as directories, not just allowed names. Idempotent.
# Logs the buckets created so a provision can be audited from its log.
seed_domain_root_dirs() {
  local _acct="$1"
  local _created=""
  local _d
  while IFS= read -r _d; do
    [ -n "$_d" ] || continue
    if [ ! -d "$_acct/$_d" ]; then
      mkdir -p "$_acct/$_d"
      _created="${_created:+$_created,}$_d"
    fi
  done < <(PROJECT_DIR="$PROJECT_DIR" python3 "$_ACCT_SCHEMA_PY" roots 2>/dev/null)
  echo "  [acct-schema] seeded-roots=${_created:-none}"
}

# reconcile_all_accounts_owned_dirs <accounts_dir>
# Standing check + backfill: for every account dir with an account.json, log the
# pre-merge present state of each declared owned dir, merge (backfill), then seed
# the vertical's root buckets so an existing account (sub-accounts are only
# provisioned once, at creation) gains the same directories a fresh one gets.
reconcile_all_accounts_owned_dirs() {
  local _accts="$1"
  [ -d "$_accts" ] || return 0
  local _acct
  for _acct in "$_accts"/*/; do
    [ -f "$_acct/account.json" ] || continue
    PROJECT_DIR="$PROJECT_DIR" python3 "$_ACCT_SCHEMA_PY" reconcile "$_acct" 2>/dev/null \
      | while IFS= read -r _line; do echo "  [acct-schema] op=reconcile ${_line}"; done
    merge_owned_dirs_into_schema "$_acct"
    seed_domain_root_dirs "$_acct"
  done
}
