#!/usr/bin/env bash
# 通用 Skill 心跳上报脚本（POSIX）。
#
# 设计原则：心跳永不阻塞业务。
# - 凡能上报的失败原因（无 SSO、网络抖动、SKILL_ID 缺失等）都落盘 pending 队列；
# - 配置全部从 monitor_config.py 取，单一事实源；
# - 退出码语义：
#     0 - 上报成功 / 已落盘 pending（业务可继续）
#     0 - MONITOR_ENABLED=0 直接 no-op
#     非 0 - 仅在内部脚本异常（如 python3 不可用）时；调用方应忽略

set +e
set -uo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
RUNTIME_DIR="${RUNTIME_DIR:-${SKILL_ROOT}/.runtime}"
PENDING_DIR="${RUNTIME_DIR}/pending_heartbeats"
STATS_FILE="${RUNTIME_DIR}/monitor_stats.json"
AUDIT_FILE="${RUNTIME_DIR}/heartbeat_audit.jsonl"
CURRENT_RUN_FILE="${CURRENT_RUN_FILE:-${RUNTIME_DIR}/current_run_id}"
CURRENT_SESSION_FILE="${CURRENT_SESSION_FILE:-${RUNTIME_DIR}/current_session_id}"
SESSION_TTL_SECONDS="${MONITOR_SESSION_TTL_SECONDS:-${SESSION_TTL_SECONDS:-28800}}"
RESET_SESSION="${MONITOR_RESET_SESSION:-${JOYCLAW_RESET_SESSION:-0}}"

mkdir -p "${RUNTIME_DIR}" "${PENDING_DIR}" 2>/dev/null

VERBOSE="${MONITOR_VERBOSE:-0}"
log_warn() { printf '[monitor-warn] %s\n' "$*" >&2; }
log_info() { [[ "${VERBOSE}" == "1" ]] && printf '[monitor-info] %s\n' "$*" >&2 || true; }
truthy() { [[ "$(printf '%s' "${1:-}" | tr '[:upper:]' '[:lower:]')" =~ ^(1|true|yes|on)$ ]]; }
normalize_runtime_id() {
  printf '%s' "${1:-}" | tr -d '\357\273\277' | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
}

file_mtime_epoch() {
  stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null || true
}

normalized_session_ttl() {
  if [[ "${SESSION_TTL_SECONDS}" =~ ^[0-9]+$ && "${SESSION_TTL_SECONDS}" -gt 0 ]]; then
    printf '%s' "${SESSION_TTL_SECONDS}"
  else
    printf '28800'
  fi
}

read_fresh_session_id() {
  if truthy "${RESET_SESSION}"; then
    rm -f "${CURRENT_SESSION_FILE}" 2>/dev/null || true
    return 0
  fi
  [[ -f "${CURRENT_SESSION_FILE}" ]] || return 0
  local mtime now ttl
  mtime="$(file_mtime_epoch "${CURRENT_SESSION_FILE}")"
  [[ -n "${mtime}" ]] || { rm -f "${CURRENT_SESSION_FILE}" 2>/dev/null || true; return 0; }
  now="$(date '+%s')"
  ttl="$(normalized_session_ttl)"
  if (( now - mtime > ttl )); then
    rm -f "${CURRENT_SESSION_FILE}" 2>/dev/null || true
    return 0
  fi
  normalize_runtime_id "$(cat "${CURRENT_SESSION_FILE}" 2>/dev/null || true)"
}

bump_stat() {
  local key="$1"
  python3 - "${STATS_FILE}" "${key}" <<'PY' 2>/dev/null || true
import json
import sys
from pathlib import Path

stats_file = Path(sys.argv[1])
key = sys.argv[2]
try:
    data = json.loads(stats_file.read_text(encoding="utf-8")) if stats_file.exists() else {}
except (OSError, json.JSONDecodeError):
    data = {}
data[key] = int(data.get(key, 0)) + 1
try:
    stats_file.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
except OSError:
    pass
PY
}

# 1. 加载配置（manifest.yaml -> SKILL.md -> .runtime/monitor.config.json -> env）
config_json="$(python3 "${SCRIPT_DIR}/monitor_config.py" --json 2>/dev/null)"
if [[ -z "${config_json}" ]]; then
  log_warn "monitor_config.py 加载失败，使用环境变量与默认值"
  config_json="{}"
fi

# 解析关键字段；解析失败回落到环境变量
read_config_field() {
  python3 - "${config_json}" "$1" <<'PY' 2>/dev/null || true
import json
import sys

try:
    data = json.loads(sys.argv[1]) if sys.argv[1] else {}
except json.JSONDecodeError:
    data = {}
print(data.get(sys.argv[2], ""))
PY
}

SKILL_ID="$(read_config_field skillId)"
SKILL_NAME="$(read_config_field skillName)"
SKILL_DESCRIPTION="$(read_config_field skillDescription)"
MONITOR_API_BASE="$(read_config_field monitorApiBase)"
MONITOR_UPLOAD_PATH="$(read_config_field monitorUploadPath)"
MONITOR_UPLOADS_PATH="$(read_config_field monitorUploadsPath)"
PROTOCOL_VERSION="$(read_config_field protocolVersion)"
HEARTBEAT_ENABLED="$(read_config_field heartbeatEnabled)"

[[ -z "${SKILL_ID}" ]]            && SKILL_ID="${SKILL_ID:-}"
[[ -z "${SKILL_NAME}" ]]          && SKILL_NAME="${SKILL_NAME:-}"
[[ -z "${SKILL_DESCRIPTION}" ]]   && SKILL_DESCRIPTION="${SKILL_DESCRIPTION:-用户上传 Skill。}"
[[ -z "${MONITOR_API_BASE}" ]]    && MONITOR_API_BASE="${MONITOR_API_BASE:-http://finbox-api.jd.com}"
[[ -z "${MONITOR_UPLOAD_PATH}" ]] && MONITOR_UPLOAD_PATH="${MONITOR_UPLOAD_PATH:-/rest/file/upload}"
[[ -z "${MONITOR_UPLOADS_PATH}" ]] && MONITOR_UPLOADS_PATH="${MONITOR_UPLOADS_PATH:-/rest/file/uploads}"
[[ -z "${PROTOCOL_VERSION}" ]]    && PROTOCOL_VERSION="1.1.0"
[[ -z "${SKILL_NAME}" && -n "${SKILL_ID}" ]] && SKILL_NAME="${SKILL_ID}"

# 2. 全局开关：MONITOR_ENABLED=0 直接 no-op
if [[ "${MONITOR_ENABLED:-1}" == "0" || "${HEARTBEAT_ENABLED}" == "False" ]]; then
  log_info "MONITOR_ENABLED=0 / heartbeatEnabled=false，跳过心跳上报"
  bump_stat "skipped_disabled"
  exit 0
fi

# 3. 业务参数（来自 send_heartbeat.py 通过环境传入）
STATUS="${STATUS:-started}"
SUMMARY="${SUMMARY:-用户新消息开始处理}"
EVENT_TYPE="${EVENT_TYPE:-user_message_started}"
PHASE="${PHASE:-user_message}"
HEARTBEAT_SEQ="${HEARTBEAT_SEQ:-1}"
ELAPSED_SECONDS="${ELAPSED_SECONDS:-0}"
ERROR_MESSAGE="${ERROR_MESSAGE:-}"
RESULT_FILES="${RESULT_FILES:-}"

RUN_ID="$(normalize_runtime_id "${RUN_ID:-}")"
SESSION_ID="$(normalize_runtime_id "${SESSION_ID:-}")"
TASK_ID="$(normalize_runtime_id "${TASK_ID:-}")"
SSO_TOKEN="${SSO_TOKEN:-}"

if [[ -z "${RUN_ID}" && -f "${CURRENT_RUN_FILE}" ]]; then
  RUN_ID="$(normalize_runtime_id "$(cat "${CURRENT_RUN_FILE}" 2>/dev/null || true)")"
fi
if [[ -z "${SESSION_ID}" ]]; then
  SESSION_ID="$(read_fresh_session_id)"
fi
[[ -z "${RUN_ID}" ]]     && RUN_ID="joyclaw-$(date '+%Y%m%d%H%M%S')-$$"
[[ -z "${SESSION_ID}" ]] && SESSION_ID="joyclaw-session-$(date '+%Y%m%d%H%M%S')-$$"
[[ -z "${TASK_ID}" ]]    && TASK_ID="${SESSION_ID}"
RUN_ID="$(normalize_runtime_id "${RUN_ID}")"
SESSION_ID="$(normalize_runtime_id "${SESSION_ID}")"
TASK_ID="$(normalize_runtime_id "${TASK_ID}")"

# 4. 文件参数检查
file_args=()
file_count=0
if [[ -n "${RESULT_FILES}" ]]; then
  while IFS= read -r result_file; do
    [[ -n "${result_file}" ]] || continue
    if [[ -f "${result_file}" ]]; then
      file_args+=("${result_file}")
      file_count=$((file_count + 1))
    else
      log_warn "result file not found, skipping: ${result_file}"
    fi
  done <<< "${RESULT_FILES}"
fi
for extra in "$@"; do
  if [[ -f "${extra}" ]]; then
    file_args+=("${extra}")
    file_count=$((file_count + 1))
  elif [[ -n "${extra}" ]]; then
    log_warn "extra file arg not found, skipping: ${extra}"
  fi
done

# 5. 构造 runtimeInfo（包含 protocolVersion）
files_for_python=()
if [[ ${file_count} -gt 0 ]]; then
  files_for_python=("${file_args[@]}")
fi

runtime_info=$(
  python3 - "${EVENT_TYPE}" "${PHASE}" "${RUN_ID}" "${SESSION_ID}" \
              "${SKILL_NAME}" "${HEARTBEAT_SEQ}" "${ELAPSED_SECONDS}" \
              "${PROTOCOL_VERSION}" "${MONITOR_API_BASE}" \
              "${MONITOR_UPLOAD_PATH}" "${MONITOR_UPLOADS_PATH}" \
              "${files_for_python[@]+"${files_for_python[@]}"}" <<'PY' 2>/dev/null
import json
import os
import sys
from datetime import datetime

(event_type, phase, run_id, session_id, skill_name,
 heartbeat_seq, elapsed_seconds, protocol_version,
 api_base, upload_path, uploads_path) = sys.argv[1:12]
output_files = sys.argv[12:]

payload = {
    "protocolVersion": protocol_version,
    "eventType": event_type,
    "eventTime": datetime.now().isoformat(timespec="seconds"),
    "runId": run_id,
    "sessionId": session_id,
    "skillName": skill_name,
    "parentSkillName": os.getenv("PARENT_SKILL_NAME", skill_name),
    "phase": phase,
    "heartbeatSeq": int(heartbeat_seq or 0),
    "elapsedSeconds": int(elapsed_seconds or 0),
    "executionContext": {
        "cwd": os.getcwd(),
        "shell": os.getenv("SHELL", ""),
        "headless": os.getenv("JOYCLAW_HEADLESS", "0") in {"1", "true", "yes"},
    },
    "outputFiles": output_files,
    "configSnapshot": {
        "monitorApiBase": api_base,
        "monitorUploadPath": upload_path,
        "monitorUploadsPath": uploads_path,
    },
}
print(json.dumps(payload, ensure_ascii=False))
PY
)

if [[ -z "${runtime_info}" ]]; then
  runtime_info='{"protocolVersion":"'${PROTOCOL_VERSION}'","eventType":"'${EVENT_TYPE}'"}'
fi

# 6. 本地审计日志与必填字段校验：缺失则落 pending 而非 fail-fast
write_audit() {
  local outcome="$1"
  local sent="$2"
  local reason="${3:-}"
  local pending_file="${4:-}"
  local http_code="${5:-}"
  local curl_exit="${6:-}"
  local source="${7:-current}"
  local audit_runtime_info="${8:-${runtime_info}}"
  local audit_status="${9:-${STATUS}}"
  local audit_summary="${10:-${SUMMARY}}"
  local audit_skill_id="${11:-${SKILL_ID}}"
  local audit_skill_name="${12:-${SKILL_NAME}}"
  local audit_run_id="${13:-${RUN_ID}}"
  local audit_session_id="${14:-${SESSION_ID}}"
  local audit_task_id="${15:-${TASK_ID}}"
  local audit_error_message="${16:-${ERROR_MESSAGE}}"
  local audit_upload_path="${17:-${MONITOR_UPLOAD_PATH}}"
  local audit_file_count="${18:-${file_count}}"
  python3 - "${AUDIT_FILE}" "${outcome}" "${sent}" "${reason}" "${pending_file}" \
              "${http_code}" "${curl_exit}" "${source}" "${audit_runtime_info}" \
              "${audit_status}" "${audit_summary}" "${audit_skill_id}" "${audit_skill_name}" \
              "${audit_run_id}" "${audit_session_id}" "${audit_task_id}" "${audit_error_message}" \
              "${audit_upload_path}" "${audit_file_count}" <<'PY' 2>/dev/null || true
import json
import sys
from datetime import datetime
from pathlib import Path

(
    audit_file, outcome, sent_raw, reason, pending_file,
    http_code_raw, curl_exit_raw, source, runtime_info_raw,
    status, summary, skill_id, skill_name, run_id,
    session_id, task_id, error_message, upload_path, file_count_raw,
) = sys.argv[1:20]

try:
    runtime_info = json.loads(runtime_info_raw) if runtime_info_raw else {}
except json.JSONDecodeError:
    runtime_info = {"raw": runtime_info_raw}

def to_int(value: str) -> int:
    try:
        return int(value)
    except (TypeError, ValueError):
        return 0

request = {
    "status": status,
    "summary": summary,
    "skillId": skill_id,
    "skillName": skill_name,
    "runId": run_id,
    "sessionId": session_id,
    "taskId": task_id,
    "eventType": runtime_info.get("eventType", ""),
    "phase": runtime_info.get("phase", ""),
    "heartbeatSeq": to_int(str(runtime_info.get("heartbeatSeq", 0))),
    "elapsedSeconds": to_int(str(runtime_info.get("elapsedSeconds", 0))),
    "uploadPath": upload_path,
    "fileCount": to_int(file_count_raw),
    "runtimeInfo": runtime_info,
}
if error_message:
    request["errorMessage"] = error_message

entry = {
    "recordedAt": datetime.now().isoformat(timespec="seconds"),
    "outcome": outcome,
    "sent": str(sent_raw).strip().lower() in {"1", "true", "yes", "on"},
    "reason": reason,
    "pendingFile": pending_file,
    "httpCode": to_int(http_code_raw),
    "curlExit": to_int(curl_exit_raw),
    "source": source,
    "request": request,
}

path = Path(audit_file)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a", encoding="utf-8") as output:
    output.write(json.dumps(entry, ensure_ascii=False, separators=(",", ":")))
    output.write("\n")
PY
}

update_run_state() {
  case "${STATUS}:${EVENT_TYPE}" in
    started:*)
      printf '%s' "${RUN_ID}" > "${CURRENT_RUN_FILE}" 2>/dev/null || true
      printf '%s' "${SESSION_ID}" > "${CURRENT_SESSION_FILE}" 2>/dev/null || true
      ;;
    success:*|failed:*)
      rm -f "${CURRENT_RUN_FILE}" 2>/dev/null || true
      ;;
  esac
}

queue_pending() {
  local reason="$1"
  local audit_http_code="${2:-}"
  local audit_curl_exit="${3:-}"
  local pending_file="${PENDING_DIR}/$(date '+%Y%m%d%H%M%S')-$$-${RANDOM:-0}.json"
  python3 - "${pending_file}" "${reason}" "${runtime_info}" "${STATUS}" "${SUMMARY}" \
              "${SKILL_ID}" "${SKILL_NAME}" "${RUN_ID}" "${SESSION_ID}" "${TASK_ID}" \
              "${ERROR_MESSAGE}" <<'PY' 2>/dev/null || true
import json
import sys

(path, reason, runtime_info, status, summary,
 skill_id, skill_name, run_id, session_id, task_id, error_message) = sys.argv[1:12]
data = {
    "queuedReason": reason,
    "runtimeInfo": runtime_info,
    "status": status,
    "summary": summary,
    "skillId": skill_id,
    "skillName": skill_name,
    "runId": run_id,
    "sessionId": session_id,
    "taskId": task_id,
    "errorMessage": error_message,
}
with open(path, "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)
PY
  log_warn "心跳已落盘 pending（${reason}）：${pending_file}"
  write_audit "queued_pending" "false" "${reason}" "${pending_file}" "${audit_http_code}" "${audit_curl_exit}" \
    "current" "${runtime_info}" "${STATUS}" "${SUMMARY}" "${SKILL_ID}" "${SKILL_NAME}" \
    "${RUN_ID}" "${SESSION_ID}" "${TASK_ID}" "${ERROR_MESSAGE}" "${MONITOR_UPLOAD_PATH}" "${file_count}"
  bump_stat "queued_pending"
  update_run_state
}

if [[ -z "${SKILL_ID}" ]]; then
  queue_pending "skill_id_missing"
  exit 0
fi

# 7. SSO Token 获取（headless 模式下软失败）
if [[ -z "${SSO_TOKEN}" ]]; then
  _token_output="$(python3 "${SCRIPT_DIR}/get_sso_token.py" 2>/dev/null)"
  _token_exit=$?
  if [[ ${_token_exit} -eq 0 && -n "${_token_output}" ]]; then
    SSO_TOKEN="${_token_output}"
  else
    queue_pending "sso_token_unavailable"
    exit 0
  fi
fi

# 8. 实际上传（curl 失败也降级落盘）
if ! command -v curl >/dev/null 2>&1; then
  queue_pending "curl_not_installed"
  exit 0
fi

post_pending_file() {
  local pending_file="$1"
  local pending_eval
  pending_eval="$(
    python3 - "${pending_file}" <<'PY' 2>/dev/null
import json
import shlex
import sys
from pathlib import Path

path = Path(sys.argv[1])
try:
    data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
    sys.exit(1)

fields = {
    "P_STATUS": data.get("status", ""),
    "P_SUMMARY": data.get("summary", ""),
    "P_RUNTIME_INFO": data.get("runtimeInfo", ""),
    "P_SKILL_ID": data.get("skillId", ""),
    "P_SKILL_NAME": data.get("skillName", ""),
    "P_RUN_ID": data.get("runId", ""),
    "P_SESSION_ID": data.get("sessionId", ""),
    "P_TASK_ID": data.get("taskId", ""),
    "P_ERROR_MESSAGE": data.get("errorMessage", ""),
}
for key, value in fields.items():
    print(f"{key}={shlex.quote(str(value or ''))}")
PY
  )"
  [[ -n "${pending_eval}" ]] || return 1
  eval "${pending_eval}"

  local p_upload_path="${MONITOR_UPLOAD_PATH}"
  local p_resp_file
  local p_http_code
  local p_curl_exit
  p_resp_file="$(mktemp 2>/dev/null || echo "/tmp/monitor_pending_resp_$$")"
  local pending_curl_args=(
    -sS
    --connect-timeout 5
    --max-time 20
    --retry 1
    -X POST
    "${MONITOR_API_BASE%/}${p_upload_path}"
    -F "skillId=${P_SKILL_ID:-${SKILL_ID}}"
    -F "runId=${P_RUN_ID:-${RUN_ID}}"
    -F "sessionId=${P_SESSION_ID:-${SESSION_ID}}"
    -F "taskId=${P_TASK_ID:-${TASK_ID}}"
    -F "skillName=${P_SKILL_NAME:-${SKILL_NAME}}"
    -F "skillDescription=${SKILL_DESCRIPTION}"
    -F "status=${P_STATUS:-started}"
    -F "summary=${P_SUMMARY:-pending replay}"
    -F "runtimeInfo=${P_RUNTIME_INFO:-{}}"
    -F "ssoToken=${SSO_TOKEN}"
    -F "protocolVersion=${PROTOCOL_VERSION}"
  )
  [[ -n "${P_ERROR_MESSAGE:-}" ]] && pending_curl_args+=(-F "errorMessage=${P_ERROR_MESSAGE}")
  p_http_code="$(curl "${pending_curl_args[@]}" -w '\n%{http_code}' -o "${p_resp_file}" 2>/dev/null | tail -n1)"
  p_curl_exit=$?
  rm -f "${p_resp_file}" 2>/dev/null
  if [[ ${p_curl_exit} -ne 0 ]]; then
    write_audit "replay_failed" "false" "curl_exit_${p_curl_exit}" "${pending_file}" "${p_http_code}" "${p_curl_exit}" \
      "pending_replay" "${P_RUNTIME_INFO:-{}}" "${P_STATUS:-started}" "${P_SUMMARY:-pending replay}" \
      "${P_SKILL_ID:-${SKILL_ID}}" "${P_SKILL_NAME:-${SKILL_NAME}}" "${P_RUN_ID:-${RUN_ID}}" \
      "${P_SESSION_ID:-${SESSION_ID}}" "${P_TASK_ID:-${TASK_ID}}" "${P_ERROR_MESSAGE:-}" \
      "${p_upload_path}" "0"
    return 1
  fi
  if [[ -n "${p_http_code}" && "${p_http_code}" =~ ^[0-9]+$ && "${p_http_code}" -ge 400 ]]; then
    write_audit "replay_failed" "false" "http_${p_http_code}" "${pending_file}" "${p_http_code}" "${p_curl_exit}" \
      "pending_replay" "${P_RUNTIME_INFO:-{}}" "${P_STATUS:-started}" "${P_SUMMARY:-pending replay}" \
      "${P_SKILL_ID:-${SKILL_ID}}" "${P_SKILL_NAME:-${SKILL_NAME}}" "${P_RUN_ID:-${RUN_ID}}" \
      "${P_SESSION_ID:-${SESSION_ID}}" "${P_TASK_ID:-${TASK_ID}}" "${P_ERROR_MESSAGE:-}" \
      "${p_upload_path}" "0"
    return 1
  fi
  rm -f "${pending_file}" 2>/dev/null || true
  write_audit "replayed_delivered" "true" "" "${pending_file}" "${p_http_code}" "${p_curl_exit}" \
    "pending_replay" "${P_RUNTIME_INFO:-{}}" "${P_STATUS:-started}" "${P_SUMMARY:-pending replay}" \
    "${P_SKILL_ID:-${SKILL_ID}}" "${P_SKILL_NAME:-${SKILL_NAME}}" "${P_RUN_ID:-${RUN_ID}}" \
    "${P_SESSION_ID:-${SESSION_ID}}" "${P_TASK_ID:-${TASK_ID}}" "${P_ERROR_MESSAGE:-}" \
    "${p_upload_path}" "0"
  bump_stat "replayed_pending"
  return 0
}

replay_pending_queue() {
  local pending_file
  shopt -s nullglob
  for pending_file in "${PENDING_DIR}"/*.json; do
    [[ -f "${pending_file}" ]] || continue
    if post_pending_file "${pending_file}"; then
      log_info "pending 心跳补发成功：${pending_file}"
    else
      log_warn "pending 心跳补发失败，保留文件：${pending_file}"
    fi
  done
  shopt -u nullglob
}

replay_pending_queue

upload_path="${MONITOR_UPLOAD_PATH}"
[[ "${file_count}" -gt 1 ]] && upload_path="${MONITOR_UPLOADS_PATH}"

curl_args=(
  -sS
  --connect-timeout 5
  --max-time 20
  --retry 1
  -X POST
  "${MONITOR_API_BASE%/}${upload_path}"
  -F "skillId=${SKILL_ID}"
  -F "runId=${RUN_ID}"
  -F "sessionId=${SESSION_ID}"
  -F "taskId=${TASK_ID}"
  -F "skillName=${SKILL_NAME}"
  -F "skillDescription=${SKILL_DESCRIPTION}"
  -F "status=${STATUS}"
  -F "summary=${SUMMARY}"
  -F "runtimeInfo=${runtime_info}"
  -F "ssoToken=${SSO_TOKEN}"
  -F "protocolVersion=${PROTOCOL_VERSION}"
)
[[ -n "${ERROR_MESSAGE}" ]] && curl_args+=(-F "errorMessage=${ERROR_MESSAGE}")

if [[ "${file_count}" -eq 1 ]]; then
  curl_args+=(-F "file=@${file_args[0]}")
elif [[ "${file_count}" -gt 1 ]]; then
  for result_file in "${file_args[@]}"; do
    curl_args+=(-F "files=@${result_file}")
  done
fi

curl_resp_file="$(mktemp 2>/dev/null || echo "/tmp/monitor_resp_$$")"
http_code="$(curl "${curl_args[@]}" -w '\n%{http_code}' -o "${curl_resp_file}" 2>/dev/null | tail -n1)"
curl_exit=$?

if [[ "${VERBOSE}" == "1" ]]; then
  log_info "HTTP ${http_code} (curl_exit=${curl_exit})"
  [[ -f "${curl_resp_file}" ]] && cat "${curl_resp_file}" >&2
fi

if [[ ${curl_exit} -ne 0 ]]; then
  queue_pending "curl_exit_${curl_exit}" "" "${curl_exit}"
elif [[ -n "${http_code}" && "${http_code}" =~ ^[0-9]+$ && "${http_code}" -ge 400 ]]; then
  queue_pending "http_${http_code}" "${http_code}" "${curl_exit}"
else
  write_audit "delivered" "true" "" "" "${http_code}" "${curl_exit}" \
    "current" "${runtime_info}" "${STATUS}" "${SUMMARY}" "${SKILL_ID}" "${SKILL_NAME}" \
    "${RUN_ID}" "${SESSION_ID}" "${TASK_ID}" "${ERROR_MESSAGE}" "${upload_path}" "${file_count}"
  bump_stat "delivered"
  log_info "心跳上报成功 status=${STATUS} event=${EVENT_TYPE}"
fi

rm -f "${curl_resp_file}" 2>/dev/null

# 9. 维护 current_run / current_session 文件
update_run_state

exit 0
