#!/bin/bash

# Daily summary script for OpenClaw user knowledge base

WORKSPACE=/root/.openclaw/workspace
DATE=$(date -d "yesterday" +"%Y-%m-%d")
MEMORY_FILE=$WORKSPACE/memory/$DATE.md
SUMMARY_FILE=$WORKSPACE/memory/summary_$DATE.md
DB_FILE=$WORKSPACE/memory.db

# Check if memory file exists
if [ ! -f $MEMORY_FILE ]; then
    echo "No memory file for $DATE. Exiting."
    exit 0
fi

# Summarize the conversation using the assistant (we'll use the current model to summarize)
summary=$(cat $MEMORY_FILE | openclaw prompt "Summarize the following conversation, extract key preferences, habits, needs, goals, and plans from the user:")

# Write summary to summary file
echo "# Daily Summary: $DATE" > $SUMMARY_FILE
echo "" >> $SUMMARY_FILE
echo "$summary" >> $SUMMARY_FILE

# Insert summary into database
sqlite3 $DB_FILE "INSERT OR REPLACE INTO preferences (key, value) VALUES ('daily_summary_$DATE', '$summary');"

# Extract user profile information (we'll need to parse this, but for now just log it)
user_profile=$(echo "$summary" | grep -E "(Name|Timezone|Preferences|Goals)" | head -10)
if [ ! -z "$user_profile" ]; then
    sqlite3 $DB_FILE "INSERT OR REPLACE INTO user_profile (id, name, timezone, notes) VALUES (1, '', '', '$user_profile');"
fi

# Update MEMORY.md with key insights
key_insights=$(echo "$summary" | grep -E "(Key|Preference|Goal|Plan)" | head -5)
if [ ! -z "$key_insights" ]; then
    echo "" >> $WORKSPACE/MEMORY.md
    echo "## Key Insights from $DATE" >> $WORKSPACE/MEMORY.md
    echo "" >> $WORKSPACE/MEMORY.md
    echo "$key_insights" >> $WORKSPACE/MEMORY.md
fi

echo "Daily summary for $DATE completed successfully."