#!/bin/bash
# Tandoor Morning Check — runs daily at 08:00 Berlin
# Exports fresh data then compares to DB; sends Telegram on differences.

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SKILL_DIR="$(dirname "$SCRIPT_DIR")"
DB="$SKILL_DIR/tandoor_foods.db"
COMPARE_OUT=$(python3 "$SCRIPT_DIR/compare_tandoor_db.py" 2>&1)
COMPARE_EXIT=$?

# Update DB no matter what
python3 "$SCRIPT_DIR/export_tandoor_to_sqlite.py" &>/dev/null

if [ $COMPARE_EXIT -ne 0 ]; then
    LAST=$(python3 -c "
import sqlite3, json
conn = sqlite3.connect('$DB')
cur = conn.execute(\"SELECT value FROM meta WHERE key='last_export'\")
row = cur.fetchone()
print(row[0] if row else 'unknown')
")
    MSG="☀️ *Tandoor Änderungen* (letzter Export: $LAST)\n\n"
    MSG+="\`\`\`\n$COMPARE_OUT\n\`\`\`"
    # Send via OpenClaw gateway log — actual Telegram send via OpenClaw agent
    echo "[tandoor-morning] Differences found, sending Telegram message..."
    openclaw exec-event '{"action":"send","channel":"telegram","message":'"$(python3 -c "import json; print(json.dumps(MSG))")'"}' 2>/dev/null || \
    echo "Differences found but Telegram send not configured. Output above."
fi
