# shellcheck shell=dash disable=2154,2034

# Variable mappings for prompt templates.
# Only outputs mappings for variables that are actually set.
# Each key must match the placeholders used in prompt/*.txt files.
___x_cmd_agent_job___prompt_mappings(){
    local jobdir="${1}"
    local descfile="${2}"
    local planfile="${3}"
    local agentfile="${4}"
    local response_file="${5}"
    local donefile="${6}"
    local iter="${7}"
    local vlid="${8}"
    local loop_context="${9}"

    local user_pwd=""
    if [ -r "$jobdir/DESC.md" ]; then
        user_pwd="$(___x_cmd_cmds grep "^Pwd: " "$jobdir/DESC.md" 2>/dev/null | ___x_cmd_cmds head -n 1)"
        user_pwd="${user_pwd#Pwd: }"
    fi
    [ -z "$user_pwd" ] && user_pwd="$jobdir"

    [ -n "$descfile" ]     && printf "DESC-FILE %s\n" "$descfile"
    [ -n "$planfile" ]     && printf "PLAN-FILE %s\n" "$planfile"
    [ -n "$agentfile" ]    && printf "AGENTS-FILE %s\n" "$agentfile"
    [ -n "$jobdir" ]       && printf "JOB-DIR %s\n" "$jobdir"
    [ -n "$user_pwd" ]     && printf "USER-PWD %s\n" "$user_pwd"
    [ -n "$response_file" ] && printf "RESPONSE-FILE %s\n" "$response_file"
    [ -n "$donefile" ]     && printf "DONE-FILE %s\n" "$donefile"
    [ -n "$iter" ]         && printf "ITER %s\n" "$iter"
    [ -n "$vlid" ]         && printf "VLID %s\n" "$vlid"
    [ -n "$loop_context" ] && printf "LOOP-CONTEXT %s\n" "$loop_context"
}

# Read a prompt template, append raw template, then append variable mappings.
# Caller must ensure required variables for the specific op are set before calling.
___x_cmd_agent_job___get_prompt(){
    local op="${1}"

    case "$op" in
        init|iter) ;;
        *) return 1 ;;
    esac

    local prompt_file="$___X_CMD_ROOT_MOD/agent/lib/job/prompts/${op}.txt"
    [ -f "$prompt_file" ] || return 1

    # Output raw template
    ___x_cmd_cmds cat "$prompt_file"

    # Output variable mappings
    printf "\n"
    ___x_cmd_agent_job___prompt_mappings \
        "$jobdir" "$descfile" "$planfile" "$agentfile" \
        "$response_file" "$donefile" "$iter" "$vlid" "$loop_context"
}
