#!/bin/bash
# CC Local Curator - runs hourly
# Silent when healthy, alerts when broken

set -e
cd "$(dirname "$0")/.."

STATE_DIR=".cc-local/.curator-state"
mkdir -p "$STATE_DIR"

# === Step 1: Check Health ===
NOW=$(date +%s)

# File freshness (compatible with both GNU and BSD stat)
get_mtime() {
  if stat -c %Y "$1" 2>/dev/null; then
    return
  elif stat -f %m "$1" 2>/dev/null; then
    return
  else
    echo 0
  fi
}

MEMORY_MTIME=$(get_mtime .cc-local/MEMORY.md)
SESSIONS_MTIME=$(get_mtime .sessions/LOCAL.md)
MEMORY_AGE_H=$(( (NOW - MEMORY_MTIME) / 3600 ))
SESSIONS_AGE_H=$(( (NOW - SESSIONS_MTIME) / 3600 ))

# Git sync check
git fetch origin --quiet
LOCAL=$(git rev-parse HEAD)
REMOTE=$(git rev-parse origin/main)
GIT_SYNCED=$([[ "$LOCAL" == "$REMOTE" ]] && echo "yes" || echo "no")

# VPS connectivity
VPS_REACHABLE=$(ssh -o ConnectTimeout=5 -o BatchMode=yes root@134.199.153.159 "echo ok" 2>/dev/null || echo "no")

# === Step 2: Analyze Patterns ===
REPEATED_PATTERNS=""
if [ -s .sessions/LOCAL.md ]; then
  # Extract action words and context, find repeats
  grep -iE '(fix|error|issue|restart|failed|broken|stuck)' .sessions/LOCAL.md 2>/dev/null | \
    sed 's/^[#*-]*//' | sort | uniq -c | sort -rn | awk '$1 >= 2' > "$STATE_DIR/patterns.txt" || true
  REPEATED_PATTERNS=$(cat "$STATE_DIR/patterns.txt" 2>/dev/null || echo "")
fi

# === Step 3: Improve ===
IMPROVEMENTS_MADE=false
if [ -n "$REPEATED_PATTERNS" ]; then
  while IFS= read -r line; do
    count=$(echo "$line" | awk '{print $1}')
    pattern=$(echo "$line" | cut -d' ' -f2-)
    # Only add if not already documented
    if ! grep -qF "$pattern" .cc-local/MEMORY.md 2>/dev/null; then
      echo "" >> .cc-local/MEMORY.md
      echo "### Pattern: $pattern" >> .cc-local/MEMORY.md
      echo "_Detected ${count}x by curator. Document the fix._" >> .cc-local/MEMORY.md
      IMPROVEMENTS_MADE=true
    fi
  done <<< "$REPEATED_PATTERNS"
fi

# === Step 4: Sync ===
SYNC_FAILED=false

# Pull latest (rebase to keep history clean, autostash local changes)
git pull --rebase --autostash --quiet || SYNC_FAILED=true

# Commit and push if changes
if [ "$IMPROVEMENTS_MADE" = true ] || ! git diff --quiet .cc-local/ 2>/dev/null; then
  git add .cc-local/
  git commit -m "Curator: auto-update $(date +%Y-%m-%d_%H:%M)" --quiet || true
  git push --quiet || SYNC_FAILED=true
fi

# Record last run
echo "$NOW" > "$STATE_DIR/last-run.txt"

# === Step 5: Report ===
ISSUES=()
[ "$MEMORY_AGE_H" -gt 24 ] && ISSUES+=("MEMORY.md not updated in ${MEMORY_AGE_H}h")
[ "$SESSIONS_AGE_H" -gt 24 ] && ISSUES+=("LOCAL.md not updated in ${SESSIONS_AGE_H}h")
[ "$GIT_SYNCED" = "no" ] && [ "$SYNC_FAILED" = false ] && ISSUES+=("Git out of sync")
[ "$VPS_REACHABLE" != "ok" ] && ISSUES+=("VPS unreachable (134.199.153.159)")
[ "$SYNC_FAILED" = true ] && ISSUES+=("Git sync failed")

# Silent when healthy
if [ ${#ISSUES[@]} -gt 0 ]; then
  echo "=== CC Local Curator Alert $(date +%Y-%m-%d_%H:%M) ==="
  printf '  - %s\n' "${ISSUES[@]}"
  exit 1
fi

exit 0
