#!/bin/bash
# Self-Improving Flywheel — every error becomes a permanent rule
#
# Usage:
#   ./scripts/flywheel-update.sh "Error description" "Rule to prevent it" "category"
#
# Categories: security, onboarding, payment, pipeline, infrastructure, general
#
# What it does:
#   1. Creates feedback memory file (Claude reads in future sessions)
#   2. Appends rule to CLAUDE.md flywheel section
#   3. Logs the action

set -uo pipefail

ERROR_DESC="${1:-}"
RULE="${2:-}"
CATEGORY="${3:-general}"

if [ -z "$ERROR_DESC" ] || [ -z "$RULE" ]; then
  echo "Usage: $0 \"error description\" \"rule to prevent it\" [category]"
  echo "Categories: security, onboarding, payment, pipeline, infrastructure, general"
  exit 1
fi

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
DATE=$(date +%Y-%m-%d)
MEMORY_DIR="/home/apibase/.claude/projects/-home-apibase-apibase/memory"
CLAUDE_MD="/home/apibase/apibase/CLAUDE.md"
LOG="/home/apibase/apibase/reports/flywheel.log"

mkdir -p "$(dirname "$LOG")"

# --- 1. Create feedback memory ---
SAFE_NAME=$(echo "$CATEGORY" | tr ' ' '_' | tr '[:upper:]' '[:lower:]')
MEMORY_FILE="${MEMORY_DIR}/feedback_flywheel_${SAFE_NAME}_${TIMESTAMP}.md"

cat > "$MEMORY_FILE" << MEMEOF
---
name: Flywheel rule — ${CATEGORY}
description: ${ERROR_DESC}
type: feedback
---

${RULE}

**Why:** ${ERROR_DESC}

**How to apply:** This rule was auto-generated by the flywheel system on ${DATE}. Apply it whenever working in the ${CATEGORY} area. If the same error pattern appears, the rule should prevent it.
MEMEOF

echo "[${TIMESTAMP}] Memory created: $(basename "$MEMORY_FILE")" >> "$LOG"

# --- 2. Append to CLAUDE.md flywheel section ---
# Check if flywheel section exists
if ! grep -q "## Flywheel Rules" "$CLAUDE_MD" 2>/dev/null; then
  # Create the section before the last section
  cat >> "$CLAUDE_MD" << 'SECTION'

---

## Flywheel Rules (auto-generated — every error becomes a rule)

_This section is automatically updated by `scripts/flywheel-update.sh`. Each entry represents an error that was found, fixed, and turned into a permanent rule to prevent recurrence._

SECTION
fi

# Append the rule
cat >> "$CLAUDE_MD" << RULEEOF
- **[${DATE}] [${CATEGORY}]** ${RULE} _(Triggered by: ${ERROR_DESC})_
RULEEOF

echo "[${TIMESTAMP}] CLAUDE.md updated with flywheel rule" >> "$LOG"

# --- 3. Update MEMORY.md index if not already tracked ---
MEMORY_INDEX="${MEMORY_DIR}/MEMORY.md"
SHORT_NAME="Flywheel: ${CATEGORY} — $(echo "$ERROR_DESC" | cut -c1-60)"
FILENAME="$(basename "$MEMORY_FILE")"
if ! grep -q "$FILENAME" "$MEMORY_INDEX" 2>/dev/null; then
  # Find the Feedback section and append
  if grep -q "## Feedback" "$MEMORY_INDEX" 2>/dev/null; then
    # Append after last feedback entry
    echo "- [${SHORT_NAME}](${FILENAME})" >> "$MEMORY_INDEX"
  fi
fi

echo "[${TIMESTAMP}] Flywheel complete: ${CATEGORY} — ${ERROR_DESC}" >> "$LOG"
echo "Flywheel rule created:"
echo "  Memory: ${MEMORY_FILE}"
echo "  CLAUDE.md: appended"
echo "  Category: ${CATEGORY}"
