#!/usr/bin/env bash
# Session start check: surface promotion-pending gotchas, unresolved hotfix
# workarounds, paused work items, and the latest session handoff. Runs as a
# SessionStart hook — warns loudly via stderr but does not block (Claude Code
# treats SessionStart exit codes advisorily).
#
# Resolves .forge at the repo root via `git rev-parse --show-toplevel` to match
# pre-compact.sh and telemetry.sh. Scans `.forge/work/*/` (typed subdirs) and
# skips `escalated`/`completed` manifests (terminal states).
#
# Session handoff: reads the LATEST aiwiki/sessions/*.md (by mtime, within
# 7 days) and surfaces:
#   - one-line summary (focus + status)
#   - any "Status: unconsumed" Checkpoints directives the next agent should act on
# The session file is created lazily by pre-compact.sh / /wrap / /dream / harden —
# NOT by this hook (avoids empty-file noise from trivial 30-second sessions).

set -u

PROJECT_ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"
FORGE_DIR="$PROJECT_ROOT/.forge"
GLOBAL_GOTCHAS="$HOME/.claude/gotchas"
WARNINGS=""

# Latest session handoff: find the most recently modified session file within
# the last 7 days and surface its focus + any unconsumed checkpoints.
if [ -d "$PROJECT_ROOT/aiwiki/sessions" ]; then
  LATEST_SESSION="$(find "$PROJECT_ROOT/aiwiki/sessions" -maxdepth 1 -type f -name '*.md' \
    ! -name 'INDEX.md' ! -name 'CLAUDE.md' \
    -mtime -7 -print0 2>/dev/null \
    | xargs -0 stat -f '%m %N' 2>/dev/null \
    | sort -rn | head -1 | cut -d' ' -f2-)"

  if [ -n "$LATEST_SESSION" ] && [ -f "$LATEST_SESSION" ]; then
    SESSION_NAME="$(basename "$LATEST_SESSION" .md)"
    FOCUS="$(grep -m1 '^focus:' "$LATEST_SESSION" 2>/dev/null | sed 's/^focus:[[:space:]]*//')"
    STATUS="$(grep -m1 '^status:' "$LATEST_SESSION" 2>/dev/null | sed 's/^status:[[:space:]]*//')"
    # Count active directives by the exact bold-header pattern. Loose patterns
    # like 'Status: unconsumed' false-positive on prose mentions of the
    # mark-consumed protocol (surfaced during dogfood, 2026-05-18).
    # `grep -c` already prints "0" when no matches; the `|| true` swallows the
    # exit-1 without appending a second "0" (which would break the -gt check
    # below — also dogfood-found).
    UNCONSUMED_COUNT="$(grep -c '^\*\*Dream directive (unconsumed):\*\*$' "$LATEST_SESSION" 2>/dev/null || true)"
    UNCONSUMED_COUNT="${UNCONSUMED_COUNT:-0}"

    WARNINGS="${WARNINGS}SESSION HANDOFF: previous session ${SESSION_NAME} (status: ${STATUS:-unknown}, focus: ${FOCUS:-unset}).\n"
    WARNINGS="${WARNINGS}  File: ${LATEST_SESSION}\n"
    if [ "$UNCONSUMED_COUNT" -gt 0 ]; then
      WARNINGS="${WARNINGS}  HARD-INTERRUPT: ${UNCONSUMED_COUNT} unconsumed checkpoint directive(s) — read ## Checkpoints in this file, act on the directive (typically: invoke support-dream), then mark the entry consumed before doing other work.\n"
    elif [ "${STATUS:-}" = "active" ]; then
      WARNINGS="${WARNINGS}  Previous session left active (no /wrap fired). Read ## Files touched / ## Next steps for context, then continue or run /wrap to finalize.\n"
    fi
  fi
fi

# Hard-interrupt: promotion-pending gotchas.
# When `support-gotcha` auto-drafts a proposed rule at the 3rd occurrence,
# the gotcha's INDEX status column flips to `promotion-pending` and a
# `Proposed Rule` block is appended to the gotcha file. The next
# session-start surfaces every such entry so the user can approve / defer /
# reject before doing other work.
#
# Match the INDEX table cell explicitly — `| promotion-pending |` — so the
# scan does not false-positive on prose that happens to mention the literal
# string ("see legend: promotion-pending entries..."). The cell can carry
# trailing whitespace before the closing pipe; allow it with `[[:space:]]*`.
PENDING_FILES=""
for index_path in "$PROJECT_ROOT/aiwiki/gotchas/INDEX.md" "$GLOBAL_GOTCHAS/INDEX.md"; do
  [ -f "$index_path" ] || continue
  if grep -Eq '\|[[:space:]]*promotion-pending[[:space:]]*\|' "$index_path" 2>/dev/null; then
    PENDING_FILES="${PENDING_FILES}${index_path}\n"
  fi
done

if [ -n "$PENDING_FILES" ]; then
  COUNT=$(printf "%b" "$PENDING_FILES" | grep -c '.' || echo 0)
  WARNINGS="${WARNINGS}HARD-INTERRUPT: ${COUNT} gotcha index file(s) contain promotion-pending entries — auto-drafted rules awaiting review.\n"
  WARNINGS="${WARNINGS}  Files:\n"
  WARNINGS="${WARNINGS}$(printf "%b" "$PENDING_FILES" | sed 's/^/    /')\n"
  WARNINGS="${WARNINGS}  Action: invoke support-gotcha to walk each promotion-pending entry (approve / defer / reject) BEFORE starting other work.\n"
fi

# Check for unresolved hotfix workarounds
if [ -d "$PROJECT_ROOT/aiwiki/gotchas" ]; then
  HOTFIX_FILES=$(grep -rl "severity: hotfix-workaround" "$PROJECT_ROOT/aiwiki/gotchas/" 2>/dev/null | while read -r f; do
    if grep -q "resolved: false" "$f" 2>/dev/null || ! grep -q "resolved: true" "$f" 2>/dev/null; then
      echo "$f"
    fi
  done)

  if [ -n "$HOTFIX_FILES" ]; then
    COUNT=$(echo "$HOTFIX_FILES" | wc -l | tr -d ' ')
    WARNINGS="${WARNINGS}WARNING: ${COUNT} unresolved hotfix workaround(s) in aiwiki/gotchas/. Run /forge-evolve or address these before starting new work.\n"
  fi
fi

# Check for paused work items across all typed subdirs
if [ -d "$FORGE_DIR/work" ]; then
  PAUSED_ITEMS=""
  for manifest in "$FORGE_DIR/work"/*/*/manifest.yaml; do
    [ -f "$manifest" ] || continue
    if grep -q 'status: paused' "$manifest" 2>/dev/null; then
      # Extract {type}/{name} from path: .../.forge/work/{type}/{name}/manifest.yaml
      TYPE_NAME="$(basename "$(dirname "$(dirname "$manifest")")")/$(basename "$(dirname "$manifest")")"
      PAUSED_ITEMS="${PAUSED_ITEMS}${TYPE_NAME}\n"
    fi
  done

  if [ -n "$PAUSED_ITEMS" ]; then
    COUNT=$(printf "%b" "$PAUSED_ITEMS" | grep -c '.' || echo 0)
    WARNINGS="${WARNINGS}WARNING: ${COUNT} paused work item(s) found. Resume with the relevant command or close them out.\n"
  fi
fi

if [ -n "$WARNINGS" ]; then
  printf "%b" "$WARNINGS" >&2
fi

exit 0
