# shellcheck shell=dash

___x_cmd_claw_agentrequest(){
    while [ "$#" -gt 0 ]; do
        case "$1" in
            --help|-h)              ___x_cmd help -m claw agentrequest; return 0 ;;
            *)                      break ;;
        esac
    done

    if [ -z "$___X_CMD_CLAW_AGENT_REFERENCE_WS" ]; then
        ___X_CMD_CLAW_AGENT_REFERENCE_WS="$HOME/.openclaw/workspace"
    fi

    local im="$1";      [ -n "$im" ] || N=claw M="Please provide IM platform name (e.g., weixin|telegram)" log:ret:64
    local chatid="$2";  [ -n "$chatid" ] || N=claw M="Please provide chatid" log:ret:64

    ___x_cmd_claw_run___ensure_im_service "$im" "$chatid" || return $?
    ___x_cmd_claw_run___agentrequest___handlemsg "$@"
}

___x_cmd_claw_run___agentrequest___handlemsg(){
    local im="$1";      [ -n "$im" ] || N=claw M="Please provide IM platform name (e.g., weixin|telegram)" log:ret:64
    local chatid="$2";  [ -n "$chatid" ] || N=claw M="Please provide chatid" log:ret:64
    local msg="$3";     [ -n "$msg" ] || N=claw M="Please provide message" log:ret:64
    local without_debug_log="${4:-}"

    if [ -n "$___X_CMD_CLAW_BOT_RECENT_STDOUT_LOG_DIR" ]; then
        local logfp="$___X_CMD_CLAW_BOT_RECENT_STDOUT_LOG_DIR/${im}-${chatid}.log"
        ___x_cmd ensurefp "$logfp"
        exec >>"$logfp" 2>&1
    fi

    local workspace_dir="$___X_CMD_CLAW_BOT_WS/${im}-${chatid}"
    local x_=""; ___x_cmd_claw_run___agentrequest___buildprompt_ "$im" "$chatid" "$msg" || return $?
    local prompt="$x_"

    local exitcode=0
    log:sub:init -i "$im:$chatid" claw "Sending request to agent request"
    local debug_flag="--debug"
    [ -n "$without_debug_log" ] && debug_flag=""
    ___x_cmd agent request  \
        --timeout 1800 \
        ${debug_flag:+$debug_flag} \
        --workspace "$workspace_dir"  \
        --reference-workspace "$___X_CMD_CLAW_AGENT_REFERENCE_WS" \
        "$prompt" || exitcode="$?"

    log:sub:fini
    if [ "$exitcode" -eq 0 ]; then
        claw:info "Successfully processed agent request for $im:$chatid"
        ___x_cmd rmrf "$___X_CMD_CLAW_BOT_HEARTBEAT/agent_unavailable"
    else
        local agent_request_stderr_file="$workspace_dir/.x-cmd/agent/request/session/metadata/stderr.txt"
        ___x_cmd_claw_run___agentrequest___notifyerror "$im" "$chatid" "$exitcode" "$agent_request_stderr_file"

        claw:error "Failed to process agent request for $im:$chatid exitcode=$exitcode workspace=$workspace_dir - marking agent as unavailable"
        ___x_cmd_claw_run___agentrequest___markunavailable
        return "$exitcode"
    fi
}

___x_cmd_claw_run___agentrequest___handleheartbeat(){
    if [ -n "$___X_CMD_CLAW_BOT_RECENT_STDOUT_LOG_DIR" ]; then
        local logfp="$___X_CMD_CLAW_BOT_RECENT_STDOUT_LOG_DIR/heartbeat.log"
        ___x_cmd ensurefp "$logfp"
        exec >>"$logfp" 2>&1
    fi

    ___x_cmd_claw_run___agentrequest___checkunavailable || return 0

    local imdir="$___X_CMD_CLAW_BOT_CONNECT_DIR"
    [ -d "$imdir" ] || {
        claw:warn "[HB] No connect directory found. Skipping heartbeat."
        return 0
    }

    local active_platforms=""
    local reply_methods=""
    local default_reply_im=""
    local default_reply_chatid=""
    local max_ts=0
    local im_count=0
    local exitcode=0

    local i j active_im active_chatid active_ts x_
    for i in "$imdir"/*; do
        [ -d "$i" ] || continue
        active_im="${i##*/}"

        # Build reply method hints for this platform (once per IM)
        case "$active_im" in
            weixin)
                reply_methods="$reply_methods
  * weixin:   x weixin send --text '<msg>'" ;;
            telegram)
                reply_methods="$reply_methods
  * telegram: x telegram send --text --chatid <CHATID> '<msg>'" ;;
            feishu)
                reply_methods="$reply_methods
  * feishu:   x feishu abot send --text --chatid <CHATID> '<msg>'" ;;
            qywx)
                reply_methods="$reply_methods
  * qywx:     x qywx abot send --text --chatid <CHATID> '<msg>'" ;;
            *)  continue ;;
        esac

        for j in "$i"/*; do
            [ -f "$j" ] || continue
            active_chatid="${j##*/}"
            read -r active_ts < "$j"
            [ -n "$active_chatid" ] || continue
            [ -n "$active_ts" ] || continue

            im_count=$((im_count + 1))

            x_=""; ___x_cmd epoch minus_ -H "$active_ts"
            active_platforms="$active_platforms
  - $active_im (chatid: $active_chatid, last_active: $x_)"

            # Find the most recently active platform
            if [ "$active_ts" -gt "$max_ts" ]; then
                max_ts="$active_ts"
                default_reply_im="$active_im"
                default_reply_chatid="$active_chatid"
            fi
        done
    done

    [ "$im_count" -gt 0 ] || {
        claw:warn "[HB] No active platforms found. Skipping heartbeat."
        return 0
    }

    local workspace_dir="$___X_CMD_CLAW_BOT_WS"

    # Check long idle state and add HEARTBEAT_OK guidance if needed
    local idle_count=0
    local heartbeat_idle_prompt=""
    local idle_file="$___X_CMD_CLAW_BOT_HEARTBEAT/idle_count"
    [ ! -f "$idle_file" ] || read -r idle_count < "$idle_file"
    if [ "${idle_count:-0}" -ge 30 ]; then
        heartbeat_idle_prompt="
LONG IDLE DETECTED — HEARTBEAT_OK MECHANISM:
This heartbeat was triggered after $idle_count minutes of inactivity. If you find there is genuinely nothing that requires the user's attention, you can silence further heartbeat agents by creating the marker file:
  \`touch $___X_CMD_CLAW_BOT_WS/HEARTBEAT_OK\`
This prevents unnecessary heartbeat wake-ups until the next user message arrives. Only do this if you are confident there are no pending tasks, reminders, or proactive insights to share."
    fi


    x_=""; ___x_cmd agent default_harness_ || {
        claw:error "Failed to get default agent harness"
        return 1
    }
    local harness="$x_"

    local agents_file="AGENTS.md"
    case "$harness" in
        claude*)    agents_file="CLAUDE.md" ;;
    esac

    # Initialize global workspace from heartbeat template if first run
    ___x_cmd_claw_run___agentrequest___syncworkspace "$workspace_dir" "$___X_CMD_ROOT_MOD/claw/lib/data/workspace/hb" "$harness"
    ___x_cmd_claw_run___agentrequest___checkworkspaceupdate "$workspace_dir" "$___X_CMD_ROOT_MOD/claw/lib/data/workspace/hb" "$harness"

    local prompt
    prompt="$(___x_cmd_cmds cat "$___X_CMD_ROOT_MOD/claw/lib/data/prompt/heartbeat.md" 2>/dev/null)" || {
        claw:error "[HB] Failed to read heartbeat prompt template"
        return 1
    }

    prompt="$prompt
<variables>
<variable name='AGENTS_FILE'>${agents_file}
</variable>
<variable name='ACTIVE_PLATFORMS'>${active_platforms}
</variable>

<variable name='DEFAULT_REPLY_IM'>${default_reply_im}
</variable>

<variable name='REPLY_METHODS'>${reply_methods}
</variable>

<variable name='WORKSPACE_DIR'>${workspace_dir}
</variable>

<variable name='CURRENT_TIME'>$(___x_cmd_claw_run___agentrequest___current_time)
</variable>
<variable name='HEARTBEAT_IDLE_PROMPT'>${heartbeat_idle_prompt}
</variable>
</variables>"

    log:sub:init -i "$im_count platform(s)" claw "[HB] Processing global heartbeat, default reply to $default_reply_im"
    ___x_cmd agent request \
        --timeout 1800 \
        --debug \
        --workspace "$workspace_dir"  \
        --reference-workspace "$___X_CMD_CLAW_AGENT_REFERENCE_WS" \
        "$prompt" || exitcode="$?"

    log:sub:fini
    if [ "$exitcode" -eq 0 ]; then
        # Heartbeat agent succeeded — clear unavailable status
        claw:debug "[HB] Heartbeat agent completed successfully"
        ___x_cmd rmrf "$___X_CMD_CLAW_BOT_HEARTBEAT/agent_unavailable"
    else
        claw:error "[HB] Global heartbeat agent request failed for $im_count platform(s)"
        ___x_cmd_claw_run___agentrequest___markunavailable
        return 1
    fi
}
