#!/bin/bash
# journal.sh — append-protocol helper. Removes friction for the AI Team
# Protocol's "three writes minimum" rule.
#
# Usage:
#   bash scripts/journal.sh "<agent>" "<short title>" "<body>"
#   bash scripts/journal.sh "<agent>" "<short title>" "<body>" --project 10_RateRight
#
# Appends to:
#   1. HQ-Vault/01_Daily/{today}.md   (creates from template if missing)
#      ## HH:MM — <agent> — <short title>
#      <body>
#
#   2. HQ-Vault/<project>/_Brain/_Log.md   (only if --project given)
#      - YYYY-MM-DD HH:MM — <agent> — <one-line synthesis from <short title>> → [[Daily/{today}#HH:MM]]
#
# Does NOT commit — that's auto-sync.sh's job (or you commit manually after
# review).

set -u

AGENT="${1:-}"
TITLE="${2:-}"
BODY="${3:-}"
PROJECT=""

# Optional --project arg
shift 3 2>/dev/null || true
while [ $# -gt 0 ]; do
  case "$1" in
    --project) PROJECT="$2"; shift 2 ;;
    *) echo "unknown arg: $1" >&2; exit 1 ;;
  esac
done

if [ -z "$AGENT" ] || [ -z "$TITLE" ] || [ -z "$BODY" ]; then
  echo "Usage: journal.sh <agent> <title> <body> [--project <name>]" >&2
  echo "Example: journal.sh claude-code-rr 'auto-approve hook' 'Tested 3 cases, all passed.' --project 10_RateRight" >&2
  exit 1
fi

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
VAULT="$ROOT/HQ-Vault"
TODAY=$(date -u +%Y-%m-%d)
NOW_HM=$(date -u +%H:%M)

DAILY="$VAULT/01_Daily/${TODAY}.md"
TEMPLATE="$VAULT/_System/Templates/Daily.md"

# 1. Ensure daily note exists
if [ ! -f "$DAILY" ]; then
  if [ -f "$TEMPLATE" ]; then
    sed "s/{{date}}/${TODAY}/g" "$TEMPLATE" > "$DAILY"
  else
    echo "# ${TODAY}" > "$DAILY"
    echo >> "$DAILY"
    echo "## Sessions" >> "$DAILY"
    echo >> "$DAILY"
  fi
  echo "created: $DAILY"
fi

# 2. Append heading + body to daily note (append-only)
{
  echo
  echo "## ${NOW_HM} — ${AGENT} — ${TITLE}"
  echo "$BODY"
} >> "$DAILY"
echo "appended to $DAILY:  '## ${NOW_HM} — ${AGENT} — ${TITLE}'"

# 3. If --project given, append a one-liner to that project's _Log.md
if [ -n "$PROJECT" ]; then
  LOG="$VAULT/${PROJECT}/_Brain/_Log.md"
  if [ ! -f "$LOG" ]; then
    echo "WARN: project log not found: $LOG (skipping log entry)" >&2
  else
    # Synthesize one-liner from title (body might be multi-line)
    {
      echo "- ${TODAY} ${NOW_HM} — ${AGENT} — ${TITLE} → [[${TODAY}#${NOW_HM}]]"
    } >> "$LOG"
    echo "appended to $LOG"
  fi
fi

echo
echo "Done. Don't forget to git add + commit when ready (or wait for auto-sync)."
