#!/usr/bin/env bash
# RE-R3c headless entry: runs the DETERMINISTIC morning brief from a scheduler's
# profile-less env (launchd/cron inherit no shell profile). No AI.
#
# The (e) slice will insert a pre-brief AI capture step here (poll -> score -> capture)
# before the `brief` call below; R3c builds ONLY the deterministic store -> artifact path.
#
# Data-path: the FOURTH sanctioned twin of store.ts:defaultStorePath / data-root.mjs:getDataRoot
# / analytics/src/utils/storage.ts:getDataRoot (the shell form of references/data-path-convention.md
# rule 1). Keep in sync. Bash 3.2-compatible: ASCII-only, all expansions quoted, no bash-4 features.
set -eu

DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$DIR"                       # so `--import tsx` resolves node_modules even under cron's $HOME cwd

NODE_BIN="${NODE_BIN:-$(command -v node 2>/dev/null || true)}"
if [ -z "$NODE_BIN" ]; then
  for c in /usr/local/bin/node /opt/homebrew/bin/node /usr/bin/node; do
    if [ -x "$c" ]; then NODE_BIN="$c"; break; fi
  done
fi

LOG="${LINKEDIN_STUDIO_DATA:-$HOME/.claude/linkedin-studio}/trends/cron.log"
mkdir -p "$(dirname "$LOG")"
TS="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

if [ -z "$NODE_BIN" ]; then
  printf '%s exit=127 node not found\n' "$TS" >> "$LOG"
  exit 127
fi

set +e
OUT="$("$NODE_BIN" --import tsx "$DIR/src/cli.ts" brief "$@" --json 2>&1)"; CODE=$?
set -e

# `brief --json` is pretty-printed (cli.ts JSON.stringify(…, null, 2)); collapse it to ONE line.
OUT="$(printf '%s' "$OUT" | tr '\n' ' ' | tr -s ' ')"
printf '%s exit=%s %s\n' "$TS" "$CODE" "$OUT" >> "$LOG"
exit "$CODE"
