# Copyright (c) 2026 Progralink. Licensed under the DevCage License — see LICENSE.
# shellcheck shell=bash

# constants.sh — Load shared data files from sandbox/shared/ into arrays.
# SCRIPT_DIR must be set by the parent script before sourcing this file.

# ── Generic list loader ───────────────────────────────────────────
# Usage: _load_list ARRAYNAME FILENAME
# Reads sandbox/shared/FILENAME into the named array.
# Skips blank lines and lines starting with #.
# Strips trailing inline comments (# ...) from each line.
_load_list() {
    local _arrname="$1" _file="${SCRIPT_DIR}/sandbox/shared/$2"
    local _line _val
    # Validate array name is a safe identifier (defense-in-depth for eval).
    # All call sites use hardcoded constants; this guard prevents misuse if
    # the function is ever called with dynamic input.
    case "$_arrname" in
        *[!a-zA-Z0-9_]*|'') echo "Error: invalid array name '$_arrname' in _load_list" >&2; return 1 ;;
    esac
    eval "${_arrname}=()"
    [ -f "$_file" ] || return 0
    while IFS= read -r _line; do
        # Strip carriage return
        _line="${_line%$'\r'}"
        # Skip blank lines and comment lines
        case "$_line" in ''|'#'*) continue ;; esac
        # Strip trailing comment (space/tab then #...)
        _val="${_line%%  #*}"
        _val="${_val%%	#*}"
        _val="${_val%% #*}"
        _val="${_val%%	#*}"
        # Strip leading/trailing whitespace
        _val="${_val#"${_val%%[! ]*}"}"
        _val="${_val%"${_val##*[! ]}"}"
        [ "$_val" != "" ] || continue
        eval "${_arrname}+=(\"\$_val\")"
    done < "$_file"
}

# ── API key loader (tag-aware) ────────────────────────────────────
# Produces:
#   _API_KEY_VARS      — all 9 keys (core + exec-only)
#   _API_KEY_VARS_CORE — 7 core keys (no exec-only tag)
_load_api_keys() {
    local _file="${SCRIPT_DIR}/sandbox/shared/api-keys.list"
    local _line _val _is_exec_only
    _API_KEY_VARS=()
    _API_KEY_VARS_CORE=()
    [ -f "$_file" ] || return 0
    while IFS= read -r _line; do
        _line="${_line%$'\r'}"
        case "$_line" in ''|'#'*) continue ;; esac
        # Detect exec-only tag before stripping comment
        _is_exec_only=0
        case "$_line" in *'# exec-only'*) _is_exec_only=1 ;; esac
        # Extract name (first token before any whitespace)
        _val="${_line%%[[:space:]]*}"
        [ "$_val" != "" ] || continue
        _API_KEY_VARS+=("$_val")
        if [ "$_is_exec_only" -eq 0 ]; then _API_KEY_VARS_CORE+=("$_val"); fi
    done < "$_file"
}

# ── Blocked env loader ────────────────────────────────────────────
# Produces:
#   _ENV_BLOCKED_NAMES    — regex: ^(NAME1|NAME2|...)=
#   _ENV_BLOCKED_PREFIXES — regex: ^(PREFIX1|PREFIX2|...)
_load_blocked_env() {
    local _names_file="${SCRIPT_DIR}/sandbox/shared/blocked-env-names.list"
    local _pfx_file="${SCRIPT_DIR}/sandbox/shared/blocked-env-prefixes.list"
    local _line _val _names_pat="" _pfx_pat=""

    if [ -f "$_names_file" ]; then
        while IFS= read -r _line; do
            _line="${_line%$'\r'}"
            case "$_line" in ''|'#'*) continue ;; esac
            _val="${_line%%[[:space:]]*}"
            [ "$_val" != "" ] || continue
            [ "$_names_pat" != "" ] && _names_pat="${_names_pat}|"
            _names_pat="${_names_pat}${_val}"
        done < "$_names_file"
    fi

    if [ -f "$_pfx_file" ]; then
        while IFS= read -r _line; do
            _line="${_line%$'\r'}"
            case "$_line" in ''|'#'*) continue ;; esac
            _val="${_line%%[[:space:]]*}"
            [ "$_val" != "" ] || continue
            [ "$_pfx_pat" != "" ] && _pfx_pat="${_pfx_pat}|"
            _pfx_pat="${_pfx_pat}${_val}"
        done < "$_pfx_file"
    fi

    _ENV_BLOCKED_NAMES="^(${_names_pat})="
    _ENV_BLOCKED_PREFIXES="^(${_pfx_pat})"
}

# ── Blocked destinations loader ───────────────────────────────────
# Produces: _BLOCKED_DESTINATIONS array
_load_blocked_destinations() {
    _load_list _BLOCKED_DESTINATIONS blocked-destinations.list
}

# ── Agent configs loader ──────────────────────────────────────────
# Produces: AGENT_CONFIGS array
# Format: HOST_PATH:RO_MOUNT:RW_MOUNT:CACHE_VOLUME
# ~/ is expanded to $HOME at load time.
_load_agent_configs() {
    local _file="${SCRIPT_DIR}/sandbox/shared/agent-configs.conf"
    local _line _val
    AGENT_CONFIGS=()
    [ -f "$_file" ] || return 0
    while IFS= read -r _line; do
        _line="${_line%$'\r'}"
        case "$_line" in ''|'#'*) continue ;; esac
        # Expand ~/ to $HOME
        # shellcheck disable=SC2088  # literal ~/ match in case pattern is intentional
        case "$_line" in
            '~/'*) _val="${HOME}/${_line#'~/'}" ;;
            *)     _val="$_line" ;;
        esac
        AGENT_CONFIGS+=("$_val")
    done < "$_file"
}

# ── Interactive commands loader ───────────────────────────────────
# Produces: _INTERACTIVE_COMMANDS array
_load_interactive_commands() {
    _load_list _INTERACTIVE_COMMANDS interactive-commands.list
}

# ── All langs loader ──────────────────────────────────────────────
# Produces: _ALL_LANGS array (canonical names only; alias lines skipped)
_load_all_langs() {
    local _file="${SCRIPT_DIR}/sandbox/shared/all-langs.list"
    local _line _val
    _ALL_LANGS=()
    [ -f "$_file" ] || return 0
    while IFS= read -r _line; do
        _line="${_line%$'\r'}"
        case "$_line" in ''|'#'*) continue ;; esac
        # Skip alias lines
        case "$_line" in *'# alias-of='*) continue ;; esac
        # Extract name (first token)
        _val="${_line%%[[:space:]]*}"
        [ "$_val" != "" ] || continue
        _ALL_LANGS+=("$_val")
    done < "$_file"
}

# ── Build-time keys loader ────────────────────────────────────────
# Produces: _BUILD_TIME_KEYS_REGEX string: ^(KEY1|KEY2|...)=
_load_build_time_keys() {
    local _file="${SCRIPT_DIR}/sandbox/shared/build-time-keys.list"
    local _line _val _pat=""
    [ -f "$_file" ] || { _BUILD_TIME_KEYS_REGEX=""; return 0; }
    while IFS= read -r _line; do
        _line="${_line%$'\r'}"
        case "$_line" in ''|'#'*) continue ;; esac
        _val="${_line%%[[:space:]]*}"
        [ "$_val" != "" ] || continue
        [ "$_pat" != "" ] && _pat="${_pat}|"
        _pat="${_pat}${_val}"
    done < "$_file"
    _BUILD_TIME_KEYS_REGEX="^(${_pat})="
}

# ── Load all data ─────────────────────────────────────────────────
_load_blocked_destinations
_load_api_keys
_load_blocked_env
_load_agent_configs
_load_interactive_commands
_load_all_langs
_load_build_time_keys
