#!/bin/bash
# cc-read-lessons.sh - Read recent Lessons Learned and extract patterns
# Called at start of every CC session
#
# Usage: ./cc-read-lessons.sh [task-keywords]
# Example: ./cc-read-lessons.sh "transcription call"

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/config.env"

LESSONS_LEARNED_DB="01d0b783-d5bf-426a-9c3f-09612708a3bc"
LESSONS_FILE="/root/rateright-growth/docs/LESSONS.md"
TASK_KEYWORDS="${1:-}"

echo "======================================"
echo "  LESSONS LEARNED - STARTUP READ"
echo "======================================"
echo ""

# First, show critical lessons from docs/LESSONS.md (the detailed file)
if [ -f "$LESSONS_FILE" ]; then
    echo "📖 CRITICAL LESSONS (from docs/LESSONS.md)"
    echo "-------------------------------------------"
    # Extract Self-Improvement Protocol section
    sed -n '/### Self-Improvement Protocol/,/### Context Management/p' "$LESSONS_FILE" | head -10
    echo ""
    echo "(Full file: $LESSONS_FILE - $(wc -l < "$LESSONS_FILE") lines)"
    echo ""
fi

# Fetch last 10 lessons (we'll filter to 5 most relevant)
LESSONS=$(curl -s -X POST "https://api.notion.com/v1/databases/${LESSONS_LEARNED_DB}/query" \
    -H "Authorization: Bearer $NOTION_API_KEY" \
    -H "Content-Type: application/json" \
    -H "Notion-Version: 2022-06-28" \
    -d '{
        "sorts": [{"property": "Date Learned", "direction": "descending"}],
        "page_size": 10
    }')

# Check if we got results
LESSON_COUNT=$(echo "$LESSONS" | python3 -c "import sys,json; print(len(json.load(sys.stdin).get('results',[])))" 2>/dev/null || echo "0")

if [ "$LESSON_COUNT" -eq 0 ]; then
    echo "No lessons learned yet. This is a fresh start!"
    echo ""
    exit 0
fi

echo "📚 RECENT LESSONS ($LESSON_COUNT found)"
echo "-----------------------------------"

# Extract and display lessons (save to temp file to avoid heredoc stdin conflict)
TEMP_FILE=$(mktemp)
echo "$LESSONS" > "$TEMP_FILE"
python3 - "$TEMP_FILE" << 'PYEOF'
import sys
import json

with open(sys.argv[1], 'r') as f:
    data = json.load(f)
results = data.get('results', [])

do_more = []
avoid = []
improve = []

for i, r in enumerate(results[:5]):
    props = r.get('properties', {})

    # Get title
    title_arr = props.get('Lesson', {}).get('title', [])
    title = title_arr[0].get('text', {}).get('content', 'Untitled') if title_arr else 'Untitled'

    # Get category
    category = props.get('Category', {}).get('select', {})
    category_name = category.get('name', 'Unknown') if category else 'Unknown'

    # Get details
    details_arr = props.get('Details', {}).get('rich_text', [])
    details = details_arr[0].get('text', {}).get('content', '') if details_arr else ''

    # Get source
    source = props.get('Source', {}).get('select', {})
    source_name = source.get('name', 'Unknown') if source else 'Unknown'

    print(f"\n{i+1}. [{category_name}] {title}")
    print(f"   Source: {source_name}")
    if details:
        # Truncate long details
        details_short = details[:200] + "..." if len(details) > 200 else details
        print(f"   Details: {details_short}")

    # Categorize for patterns
    details_lower = details.lower()
    title_lower = title.lower()

    if 'worked' in details_lower or 'success' in details_lower or 'good' in title_lower:
        do_more.append(title)
    if 'fail' in details_lower or 'error' in details_lower or 'avoid' in title_lower or 'bug' in title_lower:
        avoid.append(title)
    if 'slow' in details_lower or 'improve' in details_lower or 'better' in details_lower:
        improve.append(title)

print("\n")
print("=" * 40)
print("  PATTERN SUMMARY")
print("=" * 40)

if do_more:
    print("\n✅ DO MORE (worked well):")
    for item in do_more[:3]:
        print(f"   • {item}")

if avoid:
    print("\n❌ AVOID (caused issues):")
    for item in avoid[:3]:
        print(f"   • {item}")

if improve:
    print("\n🔄 IMPROVE (needs work):")
    for item in improve[:3]:
        print(f"   • {item}")

if not (do_more or avoid or improve):
    print("\n(No clear patterns detected yet)")

print("")
PYEOF

# Cleanup temp file
rm -f "$TEMP_FILE"

echo ""
echo "======================================"
echo "  REMEMBER"
echo "======================================"
echo ""
echo "After EVERY fix/discovery/workaround, ask yourself:"
echo ""
echo '  "Is there a lesson here?"'
echo ""
echo "If yes, do ALL THREE:"
echo "  1. Fix the system (so it CAN'T happen again)"
echo "  2. Add to docs/LESSONS.md"
echo "  3. Run: ./cc-learn-stage.sh \"Title\" \"What worked\" \"What failed\" \"What was slow\""
echo ""
echo "Don't wait for the user to prompt you."
echo ""
