#!/bin/bash
# Session auto-learn — end-of-session learning analysis
# Used by Stop hook
# Behavior controlled by LEARNING_AUTONOMY in project-constants.md:
#   Level 1 (observer): exit immediately, no action
#   Level 2 (advisor): gather session stats, output summary with suggested actions
#   Level 3 (autonomous): Level 2 + regenerate active-guidance.md from heuristics
# Exit 0 always (non-blocking)

CONSTANTS_FILE="$CLAUDE_PROJECT_DIR/.claude/project-constants.md"
HEURISTICS_FILE="$CLAUDE_PROJECT_DIR/.claude/heuristics/heuristics.md"
OBS_FILE="$CLAUDE_PROJECT_DIR/.claude/heuristics/observations.jsonl"
GUIDANCE_FILE="$CLAUDE_PROJECT_DIR/.claude/heuristics/active-guidance.md"
ERROR_LOG="$CLAUDE_PROJECT_DIR/.claude/session-errors.jsonl"
AUDIT_LOG="$CLAUDE_PROJECT_DIR/.claude/audit.log"

# Read LEARNING_AUTONOMY from project-constants.md
AUTONOMY="observer"
if [ -f "$CONSTANTS_FILE" ]; then
  LEVEL=$(grep -i 'LEARNING_AUTONOMY' "$CONSTANTS_FILE" | grep -oE '(observer|advisor|autonomous)' | head -1)
  if [ -n "$LEVEL" ]; then
    AUTONOMY="$LEVEL"
  fi
fi

# --- Level 1: Observer — exit immediately ---
if [ "$AUTONOMY" = "observer" ]; then
  exit 0
fi

# --- Level 2: Advisor — gather stats and output summary ---

# Count session errors
ERROR_COUNT=0
if [ -f "$ERROR_LOG" ]; then
  ERROR_COUNT=$(wc -l < "$ERROR_LOG" | tr -d ' ')
fi

# Count tool calls from audit log (current session only — after last SESSION_START)
TOOL_COUNT=0
if [ -f "$AUDIT_LOG" ]; then
  SESSION_START_LINE=$(grep -n 'SESSION_START' "$AUDIT_LOG" | tail -1 | cut -d: -f1)
  if [ -n "$SESSION_START_LINE" ]; then
    TOOL_COUNT=$(tail -n +"$SESSION_START_LINE" "$AUDIT_LOG" | wc -l | tr -d ' ')
  else
    TOOL_COUNT=$(wc -l < "$AUDIT_LOG" | tr -d ' ')
  fi
fi

# Count observations
OBS_COUNT=0
if [ -f "$OBS_FILE" ]; then
  OBS_COUNT=$(wc -l < "$OBS_FILE" | tr -d ' ')
fi

# Count correction signals in observations
CORRECTION_COUNT=0
if [ -f "$OBS_FILE" ]; then
  CORRECTION_COUNT=$(grep -c '"correction_signal":true' "$OBS_FILE" 2>/dev/null || echo "0")
fi

# Count active heuristics
HEURISTIC_COUNT=0
HIGH_CONFIDENCE_COUNT=0
if [ -f "$HEURISTICS_FILE" ]; then
  HEURISTIC_COUNT=$(grep -c '^\- \*\*Status\*\*: active' "$HEURISTICS_FILE" 2>/dev/null || echo "0")
  HIGH_CONFIDENCE_COUNT=$(awk '
    /^\- \*\*Confidence\*\*:/ {
      gsub(/.*\*\*Confidence\*\*: */, "")
      conf = $0 + 0
    }
    /^\- \*\*Status\*\*: active/ {
      if (conf >= 0.7) count++
    }
    END { print count + 0 }
  ' "$HEURISTICS_FILE")
fi

# Count archive files
ARCHIVE_COUNT=0
ARCHIVE_DIR="$CLAUDE_PROJECT_DIR/.claude/heuristics"
if [ -d "$ARCHIVE_DIR" ]; then
  ARCHIVE_COUNT=$(ls -1 "$ARCHIVE_DIR"/observations-archive-*.jsonl 2>/dev/null | wc -l | tr -d ' ')
fi

# Output session learning summary
echo ""
echo "## Session Learning Summary"
echo ""
echo "| Metric | Value |"
echo "|--------|-------|"
echo "| Tool calls | $TOOL_COUNT |"
echo "| Observations | $OBS_COUNT |"
echo "| Corrections detected | $CORRECTION_COUNT |"
echo "| Session errors | $ERROR_COUNT |"
echo "| Active heuristics | $HEURISTIC_COUNT |"
echo "| High-confidence (>=0.7) | $HIGH_CONFIDENCE_COUNT |"
echo "| Observation archives | $ARCHIVE_COUNT |"
echo ""

# Suggest actions based on stats
SUGGESTIONS=""
if [ "$OBS_COUNT" -gt 100 ] && [ "$HEURISTIC_COUNT" -eq 0 ]; then
  SUGGESTIONS="${SUGGESTIONS}  - Run \`/evolve\` to analyze $OBS_COUNT observations and promote patterns\n"
fi
if [ "$CORRECTION_COUNT" -gt 0 ]; then
  SUGGESTIONS="${SUGGESTIONS}  - Run \`/retrospective\` to analyze $CORRECTION_COUNT correction(s) detected this session\n"
fi
if [ "$ERROR_COUNT" -gt 3 ]; then
  SUGGESTIONS="${SUGGESTIONS}  - Run \`/retrospective --deep\` to investigate $ERROR_COUNT errors\n"
fi
if [ "$OBS_COUNT" -gt 400 ]; then
  SUGGESTIONS="${SUGGESTIONS}  - Observations nearing rotation limit ($OBS_COUNT/500). Run \`/evolve\` to promote and prune.\n"
fi

if [ -n "$SUGGESTIONS" ]; then
  echo "**Suggested actions:**"
  echo ""
  printf "$SUGGESTIONS"
  echo ""
fi

# --- Level 3: Autonomous — also regenerate active-guidance.md ---
if [ "$AUTONOMY" != "autonomous" ]; then
  exit 0
fi

# Regenerate active-guidance.md from current heuristics
mkdir -p "$(dirname "$GUIDANCE_FILE")"

if [ ! -s "$HEURISTICS_FILE" ]; then
  cat > "$GUIDANCE_FILE" << 'EMPTY_EOF'
# Active Guidance

_Auto-generated by session-auto-learn. No active heuristics yet._

Run `/evolve` after collecting observations to populate this file.
EMPTY_EOF
  echo "Active guidance: written (empty — no heuristics yet)"
  exit 0
fi

# Parse heuristics (same logic as heuristic-inject.sh)
PARSED=$(awk '
  /^### / {
    if (title != "" && status == "active") {
      printf "%s\t%s\t%s\t%s\n", confidence, title, trigger, rule
    }
    title = substr($0, 5)
    gsub(/\t/, " ", title)
    confidence = ""; trigger = ""; rule = ""; status = ""
  }
  /^\- \*\*Confidence\*\*:/ {
    gsub(/.*\*\*Confidence\*\*: */, "")
    confidence = $0 + 0
  }
  /^\- \*\*Trigger\*\*:/ {
    gsub(/.*\*\*Trigger\*\*: */, "")
    gsub(/\t/, " ")
    trigger = $0
  }
  /^\- \*\*Rule\*\*:/ {
    gsub(/.*\*\*Rule\*\*: */, "")
    gsub(/\t/, " ")
    rule = $0
  }
  /^\- \*\*Status\*\*:/ {
    gsub(/.*\*\*Status\*\*: */, "")
    gsub(/ *$/, "")
    status = $0
  }
  END {
    if (title != "" && status == "active") {
      printf "%s\t%s\t%s\t%s\n", confidence, title, trigger, rule
    }
  }
' "$HEURISTICS_FILE")

if [ -z "$PARSED" ]; then
  cat > "$GUIDANCE_FILE" << 'EMPTY_EOF'
# Active Guidance

_Auto-generated by session-auto-learn. No active heuristics yet._

Run `/evolve` after collecting observations to populate this file.
EMPTY_EOF
  echo "Active guidance: written (empty — no active heuristics)"
  exit 0
fi

# Generate active guidance file
TODAY=$(date +%Y-%m-%d)
RULES=$(echo "$PARSED" | sort -t$'\t' -k1 -rn | head -10 | awk -F'\t' '{
  printf "%d. [%.2f] When %s: %s\n", NR, $1, $3, $4
}')

cat > "$GUIDANCE_FILE" << GUIDANCE_EOF
# Active Guidance

_Auto-generated by session-auto-learn on ${TODAY}. Do not edit manually._

## Behavioral Rules (Top 10 by confidence)

${RULES}
GUIDANCE_EOF

echo "Active guidance: regenerated with $(echo "$PARSED" | wc -l | tr -d ' ') active heuristic(s)"

# Report high-confidence heuristics
if [ "$HIGH_CONFIDENCE_COUNT" -gt 0 ]; then
  echo ""
  echo "**High-confidence heuristics (>=0.7):** $HIGH_CONFIDENCE_COUNT"
  echo "$PARSED" | sort -t$'\t' -k1 -rn | awk -F'\t' '$1 >= 0.7 { printf "  - [%.2f] %s\n", $1, $2 }'
fi

exit 0
