#!/usr/bin/env bash
# memory-auto.sh — 记忆自动触发器（Phase 4）
#
# 让记忆系统"自己动起来"：
#   1. 会话开始时自动加载 Core Memory
#   2. 对话中自动判断是否需要记忆操作
#   3. 会话结束时自动 flush
#   4. 定期自动维护
#
# 用法:
#   bash scripts/memory-auto.sh on-start    # 会话开始时调用
#   bash scripts/memory-auto.sh on-message  # 收到消息时调用（传入消息）
#   bash scripts/memory-auto.sh on-end      # 会话结束时调用
#   bash scripts/memory-auto.sh on-idle     # 空闲时调用（维护）
#   bash scripts/memory-auto.sh status      # 查看自动触发状态

set -euo pipefail

WORKSPACE="$(cd "$(dirname "$0")/.." && pwd)"
MEMORY_DIR="$WORKSPACE/memory"
CORE_DIR="$MEMORY_DIR/core"
LOG="$MEMORY_DIR/.memory-auto.log"

# 加载 API Key
if [ -z "${DEEPSEEK_API_KEY:-}" ] && [ -f ~/.zshrc ]; then
  eval "$(grep '^export DEEPSEEK_API_KEY=' ~/.zshrc 2>/dev/null || true)"
fi
export DEEPSEEK_API_KEY

log() {
  echo "$(date '+%Y-%m-%d %H:%M') | $1" >> "$LOG"
}

# ── 1. 会话开始 ──────────────────────────────────────

on_start() {
  echo "🚀 记忆系统: 会话开始"
  echo ""
  
  # 加载 Core Memory
  echo "🧠 加载 Core Memory Blocks:"
  for f in "$CORE_DIR"/*.md; do
    [ -f "$f" ] || continue
    local name=$(basename "$f" .md)
    local size=$(wc -c < "$f" | tr -d ' ')
    echo "  ✅ $name ($size bytes)"
  done
  echo ""
  
  # 检查今天是否已有 daily
  local today="$MEMORY_DIR/daily/$(date +%Y-%m-%d).md"
  if [ ! -f "$today" ]; then
    echo "📅 创建今天的 daily: $(date +%Y-%m-%d)"
    echo "# $(date +%Y-%m-%d)" > "$today"
    echo "" >> "$today"
  fi
  
  # 检查 open-loops
  if [ -f "$MEMORY_DIR/registers/open-loops.md" ]; then
    open=$(grep -c '^\- \[ \]' "$MEMORY_DIR/registers/open-loops.md" 2>/dev/null || true)
    open=${open:-0}
    [ "$open" -gt 0 ] && echo "📋 有 $open 个未完成的待办"
  fi
  
  log "session_start"
  echo ""
  echo "✅ 记忆系统就绪"
}

# ── 2. 消息处理 ──────────────────────────────────────

on_message() {
  local message="${1:-}"
  [ -z "$message" ] && return
  
  # 快速判断：这条消息是否值得记忆操作
  local should_process=false
  
  # 长消息可能包含重要信息
  [ ${#message} -gt 50 ] && should_process=true
  
  # 包含关键词
  if echo "$message" | grep -qE '(记住|忘掉|偏好|纠正|决定|配置|部署|修复)'; then
    should_process=true
  fi
  
  # 包含问句（可能需要搜索）
  if echo "$message" | grep -qE '(记得|之前|上次|以前|什么|哪个|怎么|为什么)'; then
    should_process=true
  fi
  
  $should_process || return
  
  # 静默调用 Write Gate（后台）
  if [ -f "$WORKSPACE/scripts/memory-write-gate.sh" ]; then
    echo "$message" | bash "$WORKSPACE/scripts/memory-write-gate.sh" > /dev/null 2>&1 &
  fi
  
  log "message_processed: ${message:0:50}"
}

# ── 3. 会话结束 ──────────────────────────────────────

on_end() {
  echo "💾 记忆系统: 会话结束"
  echo ""
  
  # 触发 session-compact pre-compact
  if [ -f "$WORKSPACE/scripts/session-compact.sh" ]; then
    echo "📦 执行会话压缩..."
    bash "$WORKSPACE/scripts/session-compact.sh" pre-compact 2>&1 | sed 's/^/  /'
  fi
  
  # 检查是否有未保存的记忆
  local today="$MEMORY_DIR/daily/$(date +%Y-%m-%d).md"
  if [ -f "$today" ]; then
    local today_size=$(wc -c < "$today" | tr -d ' ')
    echo "  今天的 daily: $today_size bytes"
  fi
  
  log "session_end"
  echo ""
  echo "✅ 会话记忆已保存"
}

# ── 4. 空闲维护 ──────────────────────────────────────

on_idle() {
  echo "🔧 记忆系统: 空闲维护"
  echo ""
  
  # 1. 实体提取
  if [ -f "$WORKSPACE/scripts/memory-entity.sh" ]; then
    echo "🧬 实体提取..."
    bash "$WORKSPACE/scripts/memory-entity.sh" extract 2>&1 | sed 's/^/  /'
  fi
  
  # 2. 健康检查
  if [ -f "$WORKSPACE/scripts/memory-health.sh" ]; then
    echo ""
    echo "🏥 健康检查..."
    bash "$WORKSPACE/scripts/memory-health.sh" score 2>&1 | tail -5 | sed 's/^/  /'
  fi
  
  log "idle_maintenance"
  echo ""
  echo "✅ 维护完成"
}

# ── 5. 状态查看 ──────────────────────────────────────

status() {
  echo "📊 记忆自动触发状态"
  echo ""
  
  # Core Memory 状态
  echo "🧠 Core Memory:"
  for f in "$CORE_DIR"/*.md; do
    [ -f "$f" ] || continue
    local name=$(basename "$f" .md)
    local mtime=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$f" 2>/dev/null || echo "unknown")
    local size=$(wc -c < "$f" | tr -d ' ')
    echo "  $name: $size bytes ($mtime)"
  done
  
  echo ""
  echo "📋 日志 (最近 5 条):"
  [ -f "$LOG" ] && tail -5 "$LOG" || echo "  (无)"
  
  echo ""
  echo "🔧 可用脚本:"
  for script in write-gate recall entity compressor llm-router behavior health search; do
    local path="$WORKSPACE/scripts/memory-${script}.sh"
    [ -f "$path" ] && echo "  ✅ memory-${script}.sh" || echo "  ❌ memory-${script}.sh"
  done
}

# ── 入口 ─────────────────────────────────────────────

case "${1:-help}" in
  on-start) on_start ;;
  on-message) on_message "${2:-}" ;;
  on-end) on_end ;;
  on-idle) on_idle ;;
  status) status ;;
  help|*)
    echo "用法: bash scripts/memory-auto.sh <命令>"
    echo ""
    echo "命令:"
    echo "  on-start      会话开始时调用（加载 Core Memory）"
    echo "  on-message    收到消息时调用（传入消息内容）"
    echo "  on-end        会话结束时调用（flush + 压缩）"
    echo "  on-idle       空闲时调用（维护）"
    echo "  status        查看状态"
    ;;
esac
