# approval.sh — Shared approval UX for project-level init scripts and crontabs.
# shellcheck shell=bash
# Requires: warn, die, _strip_crlf (from helpers.sh).
# Used by init-scripts.sh and crontab.sh.
# Copyright (c) 2026 Progralink. Licensed under the DevCage License — see LICENSE.

# _collect_project_files DIR SCOPE_PATTERN EXT COPIES_ASSOC NAMES_ARRAY
#
# First pass: find project-scope files in DIR matching SCOPE_PATTERN (case statement match),
# copy each to a temp file (TOCTOU protection), strip CRLF, store in COPIES_ASSOC.
# Appends discovered basenames to NAMES_ARRAY.
#
# Args:
#   $1  dir          — /sandbox-init.d or /sandbox-crontab.d
#   $2  glob         — glob pattern for files in dir (e.g. "*.sh" or "*.crontab")
#   $3  scope_pat    — case pattern for project-scope files (e.g. "03-project.sh|03p*")
#   $4  ext          — temp file extension (.sh or .crontab)
#   $5  copies_var   — name of associative array variable to populate (nameref)
#   $6  names_var    — name of indexed array variable to append to (nameref)
_collect_project_files() {
    local _dir="$1" _glob="$2" _scope_pat="$3" _ext="$4"
    local -n _copies_ref="$5"
    local -n _names_ref="$6"

    local _f _base _copy
    while IFS= read -r -d '' _f; do
        [ -f "$_f" ] || continue
        _base="$(basename "$_f")"
        # shellcheck disable=SC2254  # variable holds a case pattern with | alternation
        case "$_base" in
            ${_scope_pat})
                _copy="$(mktemp "/tmp/.devcage-project-XXXXXXXX${_ext}")" || \
                    die "failed to create temp file for project file: $_base"
                cp "$_f" "$_copy"
                chmod 644 "$_copy"
                _strip_crlf "$_copy"
                _copies_ref["$_base"]="$_copy"
                _names_ref+=("$_base")
                ;;
        esac
    done < <(find "$_dir" -maxdepth 1 -name "$_glob" -print0 2>/dev/null | sort -z)
}

# _confirm_project_files NOUN PROMPT COPIES_ASSOC NAMES_ARRAY APPROVED_VAR
#
# Batch confirmation: display count, show contents of each file, prompt y/N.
# On rejection: removes all temp copies and clears both arrays.
# On SANDBOX_YOLO_CONFIG=1: auto-approves without prompting.
#
# Args:
#   $1  noun         — human label, e.g. "init script" or "crontab file"
#   $2  prompt       — prompt text, e.g. "Run these scripts?" or "Install these crontab entries?"
#   $3  copies_var   — name of associative array of temp copies (nameref)
#   $4  names_var    — name of indexed array of basenames (nameref)
#   $5  approved_var — name of integer variable to set to 1 on approval (nameref)
_confirm_project_files() {
    local _noun="$1" _prompt="$2"
    # shellcheck disable=SC2178  # namerefs targeting arrays; shellcheck misdetects type
    local -n _copies_ref="$3"
    # shellcheck disable=SC2178  # nameref targeting an array; shellcheck misdetects type
    local -n _names_ref="$4"
    local -n _approved_ref="$5"

    if [ "${SANDBOX_YOLO_CONFIG:-0}" = "1" ]; then
        _approved_ref=1
        return
    fi

    local _answer _pf
    echo "" >&2
    echo "══════════════════════════════════════════════════════════" >&2
    echo "  Found ${#_names_ref[@]} project ${_noun}(s) — contents:" >&2
    echo "══════════════════════════════════════════════════════════" >&2
    for _pf in "${_names_ref[@]}"; do
        echo "── ${_pf} ──" >&2
        cat "${_copies_ref[$_pf]}" >&2
        echo "" >&2
    done
    echo "══════════════════════════════════════════════════════════" >&2
    if read -r -p "${_prompt} [y/N] " _answer </dev/tty 2>/dev/null; then
        case "$_answer" in
            [yY]|[yY][eE][sS]) _approved_ref=1 ;;
            *) echo "Skipping project ${_noun}s" >&2 ;;
        esac
    else
        echo "Non-interactive — skipping project ${_noun}s (use --yolo-config to auto-approve)" >&2
    fi

    if [ "$_approved_ref" != "1" ]; then
        for _pf in "${_names_ref[@]}"; do
            rm -f "${_copies_ref[$_pf]}"
        done
        _copies_ref=()
        _names_ref=()
    fi
}
