#!/bin/bash
# update-stage.sh — Update statusline stageDescription in bridge file
# Usage:
#   bash ~/.claude/evolv-coder-kit/update-stage.sh "Interview (1/7)"  # set stage
#   bash ~/.claude/evolv-coder-kit/update-stage.sh                     # reset to "Ready"
#
# Reads CLAUDE_SESSION_ID env var to locate the bridge file.
# Silent no-op if jq is missing. No stdout/stderr output.

# ─── Graceful degradation: require jq ────────────────────────────────────────
command -v jq >/dev/null 2>&1 || exit 0

# ─── Session ID ──────────────────────────────────────────────────────────────
# Priority: CLAUDE_SESSION_ID env var > .claude/sessions/ derived hash match
#           > .claude/sessions/ most recent > .claude/.session-id file > derived hash
if [ -n "$CLAUDE_SESSION_ID" ]; then
  SESSION_ID="$CLAUDE_SESSION_ID"
else
  DERIVED_HASH="$(printf '%s%s' "$PWD" "$PPID" | shasum -a 256 2>/dev/null | head -c 8 || echo "default")"
  SESSIONS_DIR="${CLAUDE_PROJECT_DIR:-.}/.claude/sessions"

  if [ -d "$SESSIONS_DIR" ] && [ -f "$SESSIONS_DIR/${DERIVED_HASH}.json" ]; then
    # Exact match for this session's derived hash
    SESSION_ID="$DERIVED_HASH"
  elif [ -d "$SESSIONS_DIR" ]; then
    # Fallback: most recently modified session file
    NEWEST="$(find "$SESSIONS_DIR" -maxdepth 1 -name '*.json' -printf '%T@ %p\n' 2>/dev/null | sort -rn | head -1 | cut -d' ' -f2-)"
    # macOS fallback: -printf not available
    if [ -z "$NEWEST" ]; then
      NEWEST="$(find "$SESSIONS_DIR" -maxdepth 1 -name '*.json' -exec stat -f '%m %N' {} \; 2>/dev/null | sort -rn | head -1 | cut -d' ' -f2-)"
    fi
    if [ -n "$NEWEST" ]; then
      SESSION_ID="$(basename "$NEWEST" .json)"
    elif [ -f ".claude/.session-id" ]; then
      SESSION_ID="$(tr -d '[:space:]' < .claude/.session-id)"
    elif [ -f "${PWD}/.claude/.session-id" ]; then
      SESSION_ID="$(tr -d '[:space:]' < "${PWD}/.claude/.session-id")"
    else
      SESSION_ID="$DERIVED_HASH"
    fi
  elif [ -f ".claude/.session-id" ]; then
    SESSION_ID="$(tr -d '[:space:]' < .claude/.session-id)"
  elif [ -f "${PWD}/.claude/.session-id" ]; then
    SESSION_ID="$(tr -d '[:space:]' < "${PWD}/.claude/.session-id")"
  else
    SESSION_ID="$DERIVED_HASH"
  fi
fi
BRIDGE_FILE="${TMPDIR:-/tmp}/claude-ctx-${SESSION_ID}.json"

# ─── Stage description: argument or "Ready" ─────────────────────────────────
STAGE_DESC="${1:-Ready}"

# ─── Update bridge file (atomic temp+mv write) ──────────────────────────────
if [ -f "$BRIDGE_FILE" ]; then
  # Update existing bridge file — preserve all other fields
  BRIDGE_TMP="${BRIDGE_FILE}.stage.tmp"
  if jq --arg sd "$STAGE_DESC" '.stageDescription = $sd' "$BRIDGE_FILE" \
       > "$BRIDGE_TMP" 2>/dev/null; then
    mv "$BRIDGE_TMP" "$BRIDGE_FILE" 2>/dev/null
  else
    rm -f "$BRIDGE_TMP" 2>/dev/null
  fi
else
  # Create minimal bridge file
  BRIDGE_TMP="${BRIDGE_FILE}.stage.tmp"
  NOW=$(date +%s)
  if jq -n \
       --arg sd "$STAGE_DESC" \
       --argjson ts "$NOW" \
       --arg sid "$SESSION_ID" \
       '{contextPercent: null, stageDescription: $sd, gitBranch: "", timestamp: $ts, sessionId: $sid}' \
       > "$BRIDGE_TMP" 2>/dev/null; then
    mv "$BRIDGE_TMP" "$BRIDGE_FILE" 2>/dev/null
  else
    rm -f "$BRIDGE_TMP" 2>/dev/null
  fi
fi

exit 0
