#!/bin/bash
# task-timer cleanup wrapper
#
# Cron registration: Add the following line to your crontab (crontab -e):
# 0 * * * * bash /home/jay/workspace/scripts/cleanup-stale-tasks.sh

WORKSPACE=/home/jay/workspace
LOG_DIR=$WORKSPACE/memory/logs
LOG_FILE=$LOG_DIR/cleanup-stale.log
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')

# Create logs directory if it doesn't exist
if [ ! -d "$LOG_DIR" ]; then
    mkdir -p "$LOG_DIR"
    if [ $? -ne 0 ]; then
        echo "[$TIMESTAMP] ERROR: Failed to create logs directory: $LOG_DIR" >&2
        exit 1
    fi
fi

echo "[$TIMESTAMP] Starting stale task cleanup..." >> "$LOG_FILE"

result=$(python3 "$WORKSPACE/memory/task-timer.py" cleanup --running-hours 24 --reserved-minutes 60 2>&1)
exit_code=$?

echo "[$TIMESTAMP] Result: $result" >> "$LOG_FILE"

# Extract cleaned_count from JSON result
cleaned_count=$(echo "$result" | python3 -c "import sys,json; print(json.load(sys.stdin).get('cleaned_count',0))" 2>/dev/null || echo "0")

# Notify only when stale tasks found
if [ "$cleaned_count" -gt 0 ] 2>/dev/null; then
    echo "[$TIMESTAMP] ALERT: $cleaned_count stale task(s) cleaned. Sending notification..." >> "$LOG_FILE"
    cokacdir --sendfile "$LOG_FILE" --chat 6937032012 --key c119085addb0f8b7 2>/dev/null
fi

if [ $exit_code -ne 0 ]; then
    echo "[$TIMESTAMP] ERROR: cleanup failed with exit code $exit_code" >> "$LOG_FILE"
    cokacdir --sendfile "$LOG_FILE" --chat 6937032012 --key c119085addb0f8b7 2>/dev/null
fi

# Log file size limit (keep only last 500 lines if exceeds 1000 lines)
if [ $(wc -l < "$LOG_FILE") -gt 1000 ]; then
    tail -500 "$LOG_FILE" > "$LOG_FILE.tmp" && mv "$LOG_FILE.tmp" "$LOG_FILE"
fi

echo "[$TIMESTAMP] Cleanup done." >> "$LOG_FILE"

exit $exit_code
