#!/usr/bin/env bash
# build-journal: append one entry to a product's Build journal, mirror it to the
# team's Google Chat space, and record it as a structured event for a Build
# operations UI. Installed by the tautline-ops build-heartbeat skill.
#
# usage:
#   build-journal --product <slug> --run <RUN> --kind <kind> [--item ID]... [--pr N]... [--state S] "text"
#   echo "text" | build-journal --product <slug> --run <RUN> --kind <kind>
#
#   --product  product slug; loads ~/.config/build-heartbeat/<slug>.env
#              (default: $BUILD_JOURNAL_PRODUCT, else "default")
#   --run      the run stamp the heartbeat prompt defines (e.g. 20261109-0808ET);
#              also the Google Chat thread key, so one run = one thread
#   --kind     wake | found | plan | progress | blocked | closed | finish | note
#   --item ID  tracker item this entry is about, as the tracker writes it (3605,
#              PROJ-142); repeat, or comma-separate. Starts with a letter or digit.
#   --pr N     pull request number this entry is about; repeat, or comma-separate
#   --state S  selected | building | pr-open | reviewed | in-batch | queued | evicted |
#              merged | on-dev | looked | awaiting-signoff | blocked | unblocked | closed
#   --session  Claude session id (default: $CLAUDE_CODE_HOST_SESSION_ID)
#   --no-chat  journal to disk only (tests; a live run's wake and a healthy
#              check's found entry)
#   --thread <key>  override the chat thread key (default: the run stamp)
#
# Config file ~/.config/build-heartbeat/<slug>.env (plain KEY=value lines, never
# executed; absolute paths only, "~" is not expanded):
#   BUILD_JOURNAL_DIR=/abs/path/to/journal      (required)
#   BUILD_JOURNAL_TZ=America/New_York           (IANA zone humans read; default shown)
#   BUILD_JOURNAL_WEBHOOK_FILE=/abs/path        (default ~/.config/build-heartbeat/<slug>.webhook)
# The webhook file holds one Google Chat incoming-webhook URL, mode 600. A
# BUILD_JOURNAL_GOOGLE_CHAT_WEBHOOK environment variable overrides it.
#
# Disk:   $BUILD_JOURNAL_DIR/<YYYY-MM-DD>.md, one bullet per entry, local day.
# Events: $BUILD_JOURNAL_DIR/events/<YYYY-MM-DD>.jsonl, schema build-journal-event/v2.
# Chat:   one message per entry, threaded by run. Delivery log: $BUILD_JOURNAL_DIR/.chat.log
# Exit:   0 whenever the call was well formed, even if a write or the chat post
#         failed (the output says what failed); 2 for a usage or config error.
set -u

usage_end=36
if [ $# -eq 1 ]; then
  case "$1" in -h|--help) sed -n "2,${usage_end}p" "$0"; exit 0 ;; esac
fi

product="${BUILD_JOURNAL_PRODUCT:-default}"
run="" kind="note" thread="" no_chat=0 state=""
session="${CLAUDE_CODE_HOST_SESSION_ID:-}"
items=() prs=() msg_args=()

add_list() { # $1 = array name, $2 = "A" or "A,B"; $3 = digits|id; strips a leading '#'
  local v parts
  IFS=', ' read -r -a parts <<< "$2"
  for v in ${parts[@]+"${parts[@]}"}; do
    v="${v#\#}"
    case "$3:$v" in
      *:|digits:*[!0-9]*|id:[!A-Za-z0-9]*|id:*[!A-Za-z0-9._-]*)
        echo "build-journal: ignoring '$v' (not a valid $1 value)" >&2 ;;
      *) eval "$1+=(\"\$v\")" ;;  # safe: $v holds only letters, digits, . _ -
    esac
  done
}

while [ $# -gt 0 ]; do
  case "$1" in
    --product|--run|--kind|--item|--pr|--state|--session|--thread)
      if [ $# -lt 2 ]; then echo "build-journal: $1 needs a value" >&2; exit 2; fi
      case "$1" in
        --product) product="$2" ;;
        --run) run="$2" ;;
        --kind) kind="$2" ;;
        --item) add_list items "$2" id ;;
        --pr) add_list prs "$2" digits ;;
        --state) state="$2" ;;
        --session) session="$2" ;;
        --thread) thread="$2" ;;
      esac
      shift 2 ;;
    --no-chat) no_chat=1; shift ;;
    --) shift; msg_args+=("$@"); break ;;
    *) msg_args+=("$1"); shift ;;
  esac
done

case "$product" in *[!A-Za-z0-9._-]*|'') echo "build-journal: bad --product '$product'" >&2; exit 2 ;; esac

# Load the product config without executing it: only the four known keys.
conf_dir="${BUILD_HEARTBEAT_CONFIG_DIR:-$HOME/.config/build-heartbeat}"
conf="$conf_dir/$product.env"
conf_get() {
  [ -f "$conf" ] || return 0
  tr -d '\r' < "$conf" | grep -E "^(export )?$1=" | tail -n1 \
    | sed -E "s/^(export )?$1=//; s/^[\"']//; s/[\"']\$//"
}
JOURNAL_DIR="${BUILD_JOURNAL_DIR:-$(conf_get BUILD_JOURNAL_DIR)}"
MACHINE_NAME="${BUILD_JOURNAL_MACHINE:-$(conf_get BUILD_JOURNAL_MACHINE)}"
TZ_NAME="${BUILD_JOURNAL_TZ:-$(conf_get BUILD_JOURNAL_TZ)}"
TZ_NAME="${TZ_NAME:-America/New_York}"
webhook_file="${BUILD_JOURNAL_WEBHOOK_FILE:-$(conf_get BUILD_JOURNAL_WEBHOOK_FILE)}"
webhook_file="${webhook_file:-$conf_dir/$product.webhook}"
if [ -z "$JOURNAL_DIR" ]; then
  echo "build-journal: no journal folder for product '$product' (set BUILD_JOURNAL_DIR in $conf)" >&2
  exit 2
fi
case "$JOURNAL_DIR" in /*) ;; *) echo "build-journal: BUILD_JOURNAL_DIR must be an absolute path" >&2; exit 2 ;; esac

if [ ${#msg_args[@]} -gt 0 ]; then
  message="${msg_args[*]}"
else
  message="$(cat)"
fi
message="$(printf '%s' "$message" | sed -e 's/[[:space:]]*$//')"
if [ -z "$message" ]; then
  echo "build-journal: empty message" >&2
  exit 2
fi
[ -n "$run" ] || run="unknown-run"
[ -n "$thread" ] || thread="$run"

case "$kind" in
  wake|found|plan|progress|blocked|closed|finish|note) ;;
  *) echo "build-journal: unknown kind '$kind', using note" >&2; kind="note" ;;
esac
case "$state" in
  ''|selected|building|pr-open|reviewed|in-batch|queued|evicted|merged|on-dev|looked|awaiting-signoff|blocked|unblocked|closed) ;;
  *) echo "build-journal: unknown state '$state', dropped" >&2; state="" ;;
esac

JQ="$(command -v jq || true)"
problems=()

# Date helpers that work with BSD (macOS) and GNU (Linux) date.
if date -d @0 +%s >/dev/null 2>&1; then gnu_date=1; else gnu_date=0; fi
fmt_epoch() { # $1 epoch, $2 format, $3 zone
  if [ $gnu_date -eq 1 ]; then TZ="$3" date -d "@$1" "$2"; else TZ="$3" date -r "$1" "$2"; fi
}
parse_stamp() { # $1 "YYYYMMDDHHMM", $2 zone it is written in -> epoch
  local s="$1"
  if [ $gnu_date -eq 1 ]; then
    TZ="$2" date -d "${s:0:4}-${s:4:2}-${s:6:2} ${s:8:2}:${s:10:2}" +%s 2>/dev/null
  else
    TZ="$2" date -j -f '%Y%m%d%H%M%S' "${s}00" +%s 2>/dev/null
  fi
}
human_fmt='+%b %-d, %-I:%M %p %Z'

# The run stamp is an id; show it as the local moment the run started. Accepts
# YYYYMMDD-HHMM<zone label> (local) and YYYYMMDDTHHMMZ (UTC, older runs).
run_display() {
  local r="$1" epoch=""
  case "$r" in
    [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9]Z*)
      epoch="$(parse_stamp "${r:0:8}${r:9:4}" UTC)" ;;
    [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]*)
      epoch="$(parse_stamp "${r:0:8}${r:9:4}" "$TZ_NAME")" ;;
  esac
  if [ -n "$epoch" ]; then fmt_epoch "$epoch" "$human_fmt" "$TZ_NAME"; else printf '%s' "$r"; fi
}

now_epoch="$(date +%s)"
ts_utc="$(fmt_epoch "$now_epoch" '+%Y-%m-%dT%H:%M:%SZ' UTC)"
ts_local="$(fmt_epoch "$now_epoch" '+%Y-%m-%dT%H:%M:%S%z' "$TZ_NAME")"
day="$(fmt_epoch "$now_epoch" '+%Y-%m-%d' "$TZ_NAME")"
clock="$(fmt_epoch "$now_epoch" '+%-I:%M %p %Z' "$TZ_NAME")"
run_label="$(run_display "$run")"

file="$JOURNAL_DIR/$day.md"
events="$JOURNAL_DIR/events/$day.jsonl"
mkdir -p "$JOURNAL_DIR/events" 2>/dev/null || problems+=("cannot create $JOURNAL_DIR")

# Disk entry: first line on the bullet, continuation lines indented.
first="$(printf '%s\n' "$message" | sed -n '1p')"
rest="$(printf '%s\n' "$message" | sed -n '2,$p')"
md_ok=1
{
  if [ ! -s "$file" ]; then
    printf '# %s build journal, %s (times in %s)\n\n' "$product" "$day" "$TZ_NAME"
  fi
  printf -- '- **%s** · run of %s · %s: %s\n' "$clock" "$run_label" "$kind" "$first"
  if [ -n "$rest" ]; then
    printf '%s\n' "$rest" | sed -e 's/^/  /'
  fi
} >> "$file" 2>/dev/null || { md_ok=0; problems+=("journal write FAILED ($file)"); }

# Chat mirror. chat_status: posted | failed | skipped | not-configured | no-jq
chat_status="skipped" chat_message=""
if [ "$no_chat" -eq 0 ]; then
  webhook="${BUILD_JOURNAL_GOOGLE_CHAT_WEBHOOK:-}"
  if [ -z "$webhook" ] && [ -f "$webhook_file" ]; then
    webhook="$(head -n1 "$webhook_file" | tr -d '[:space:]')"
  fi
  if [ -z "$webhook" ]; then
    chat_status="not-configured"
  elif [ -z "$JQ" ] || ! command -v curl >/dev/null 2>&1; then
    chat_status="no-jq"
    problems+=("chat skipped: jq and curl are required")
  else
    case "$webhook" in
      *\?*) post_url="${webhook}&messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD" ;;
      *)    post_url="${webhook}?messageReplyOption=REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD" ;;
    esac
    text="$(printf '*%s* · %s · run of %s\n%s' "$kind" "$clock" "$run_label" "$message")"
    # Google Chat rejects very long messages; the full text stays on disk.
    if [ "${#text}" -gt 3800 ]; then
      text="${text:0:3800}
… (truncated; full entry in the journal)"
    fi
    body="$("$JQ" -cn --arg t "$text" --arg k "$thread" '{text: $t, thread: {threadKey: $k}}')"
    log="$JOURNAL_DIR/.chat.log"
    # The URL goes to curl on stdin, never on its command line, so `ps` cannot see it.
    resp="$(printf 'url = "%s"\n' "$post_url" | curl -sS --max-time 20 -K - -X POST \
      -H 'Content-Type: application/json; charset=UTF-8' --data "$body" 2>&1)"
    rc=$?
    if [ $rc -eq 0 ] && printf '%s' "$resp" | "$JQ" -e '.name' >/dev/null 2>&1; then
      chat_status="posted"
      chat_message="$(printf '%s' "$resp" | "$JQ" -r '.name')"
      printf '%s run=%s kind=%s posted %s\n' "$ts_utc" "$run" "$kind" "$chat_message" >> "$log" 2>/dev/null
    else
      chat_status="failed"
      problems+=("Google Chat post FAILED (see $log)")
      # Never log the request URL: it carries the webhook key and token.
      printf '%s run=%s kind=%s FAILED rc=%s %s\n' "$ts_utc" "$run" "$kind" "$rc" \
        "$(printf '%s' "$resp" | head -c 300 | tr '\n' ' ' | sed -E 's/(key|token)=[^&" ]*/\1=REDACTED/g')" >> "$log" 2>/dev/null
    fi
  fi
fi

# Structured event for the Build UI. Item ids are strings; PR numbers are numbers.
event_ok=0
if [ -z "$JQ" ]; then
  problems+=("event skipped: jq is required")
else
  items_json="$(printf '%s\n' ${items[@]+"${items[@]}"} | "$JQ" -R 'select(length>0)' | "$JQ" -cs '.')"
  prs_json="$(printf '%s\n' ${prs[@]+"${prs[@]}"} | "$JQ" -R 'select(length>0) | tonumber' | "$JQ" -cs '.')"
  if "$JQ" -cn \
    --arg product "$product" --arg ts "$ts_utc" --arg tsLocal "$ts_local" --arg tz "$TZ_NAME" \
    --arg day "$day" --arg run "$run" --arg thread "$thread" --arg sessionId "$session" \
    --arg kind "$kind" --argjson items "$items_json" --argjson prs "$prs_json" \
    --arg state "$state" --arg text "$message" --arg chat "$chat_status" \
    --arg chatMessage "$chat_message" --arg host "$(printf '%s' "${MACHINE_NAME:-$(hostname -s 2>/dev/null || hostname)}" | tr '[:upper:]' '[:lower:]')" \
    '{schema: "build-journal-event/v2", product: $product, ts: $ts, tsLocal: $tsLocal,
      tz: $tz, day: $day, run: $run, thread: $thread,
      sessionId: (if $sessionId == "" then null else $sessionId end),
      kind: $kind, items: $items, prs: $prs,
      state: (if $state == "" then null else $state end),
      text: $text, chat: $chat,
      chatMessage: (if $chatMessage == "" then null else $chatMessage end),
      host: $host}' >> "$events" 2>/dev/null; then
    event_ok=1
  else
    problems+=("event write FAILED ($events)")
  fi
fi

summary="journaled: $file"
[ $md_ok -eq 1 ] || summary="journal NOT written"
[ $event_ok -eq 1 ] && summary="$summary; event recorded"
case "$chat_status" in
  posted) summary="$summary; posted to Google Chat (thread $thread)" ;;
  not-configured) summary="$summary (chat not configured: no webhook for '$product')" ;;
  skipped) summary="$summary (chat skipped by --no-chat)" ;;
esac
echo "$summary"
for p in ${problems[@]+"${problems[@]}"}; do echo "build-journal: $p" >&2; done
exit 0
