#!/usr/bin/env bash
set -euo pipefail

id="${1:-}"
runner="${2:-}"
exit_code="${3:-1}"
log_file="${4:-}"
job_file="${5:-}"

state_dir="$(cd "$(dirname "$job_file")/.." && pwd)"
completed_file="$state_dir/completed.ndjson"
now="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"

# Notification settings (override via env if needed)
notify_enabled="${PIPO_NOTIFY_ENABLED:-1}"
notify_channel="${PIPO_NOTIFY_CHANNEL:-telegram}"
notify_target="${PIPO_NOTIFY_TARGET:-842987156}"
notify_preview_chars="${PIPO_NOTIFY_PREVIEW_CHARS:-220}"

last_line=""
preview=""
if [[ -f "$log_file" ]]; then
  last_line="$(tail -n 1 "$log_file" | tr '\t' ' ' | tr '\r' ' ')"
  preview="$(tail -n 3 "$log_file" 2>/dev/null | tr '\r\n' ' ' | sed -E 's/[[:space:]]+/ /g' | cut -c1-"$notify_preview_chars")"
fi

jq -nc \
  --arg time "$now" \
  --arg id "$id" \
  --arg runner "$runner" \
  --argjson exit_code "$exit_code" \
  --arg log_file "$log_file" \
  --arg job_file "$job_file" \
  --arg last_line "$last_line" \
  '{time:$time,id:$id,runner:$runner,exit_code:$exit_code,log_file:$log_file,job_file:$job_file,last_line:$last_line}' >> "$completed_file"

notify_status="skipped"
if [[ "$notify_enabled" == "1" ]] && [[ -n "$notify_target" ]] && command -v openclaw >/dev/null 2>&1; then
  if [[ "$exit_code" -eq 0 ]]; then
    emoji="✅"
    status_label="done"
  else
    emoji="❌"
    status_label="failed"
  fi

  msg="$emoji Job ${status_label} | ${runner} | id=${id} | exit=${exit_code}"
  if [[ -n "$preview" ]]; then
    msg="$msg
$preview"
  fi

  if openclaw message send \
    --channel "$notify_channel" \
    --target "$notify_target" \
    --message "$msg" \
    --silent \
    >/dev/null 2>&1; then
    notify_status="ok"
  else
    notify_status="fail"
  fi
fi

echo "[$now] done id=$id runner=$runner exit=$exit_code notify=$notify_status"