#!/bin/bash
# Move telegram archives + apply pending learnings. Runs every 5 min via cron.
set -euo pipefail

STAGING="/opt/teleo-eval/telegram-archives"
MAIN="/opt/teleo-eval/workspaces/main"
LOCKFILE="/opt/teleo-eval/workspaces/.main-worktree.lock"
LEARNINGS="$MAIN/agents/rio/learnings.md"
PENDING="$STAGING/pending-learnings.jsonl"

# Check if there's anything to do
HAS_ARCHIVES=$(ls "$STAGING"/*.md 2>/dev/null | head -1) || true
HAS_LEARNINGS=""
[ -s "$PENDING" ] && HAS_LEARNINGS="yes"

[ -z "$HAS_ARCHIVES" ] && [ -z "$HAS_LEARNINGS" ] && exit 0

# Acquire worktree lock
exec 9>"$LOCKFILE"
if ! flock -n 9; then
    exit 0  # Lock held — skip this cycle
fi

CHANGED=0

# Move archive files
for f in $STAGING/*.md; do
    [ -f "$f" ] || continue
    mv "$f" "$MAIN/inbox/queue/"
    CHANGED=$((CHANGED + 1))
done

# Apply pending learnings to learnings.md
if [ -s "$PENDING" ]; then
    while IFS= read -r line; do
        category=$(echo "$line" | python3 -c "import sys,json; print(json.load(sys.stdin).get('category','factual'))" 2>/dev/null || echo "factual")
        correction=$(echo "$line" | python3 -c "import sys,json; print(json.load(sys.stdin).get('correction',''))" 2>/dev/null || echo "")
        date_str=$(date +%Y-%m-%d)
        [ -z "$correction" ] && continue

        # Append to the right section
        case "$category" in
            communication)
                # Find ## Communication Notes and append after it
                sed -i "/^## Communication Notes/a - [$date_str] $correction" "$LEARNINGS"
                ;;
            structured_data)
                sed -i "/^## Structured Data/a - [$date_str] $correction" "$LEARNINGS"
                ;;
            *)
                sed -i "/^## Factual Corrections/a - [$date_str] $correction" "$LEARNINGS"
                ;;
        esac
        CHANGED=$((CHANGED + 1))
    done < "$PENDING"
    rm -f "$PENDING"
fi

if [ "$CHANGED" -gt 0 ]; then
    cd "$MAIN"
    git add -A inbox/queue/ agents/rio/learnings.md
    git commit -m "rio: sync $CHANGED item(s) from telegram staging

Pentagon-Agent: Epimetheus <3D35839A-7722-4740-B93D-51157F7D5E70>" 2>/dev/null || true
    for attempt in 1 2 3; do
        git pull --rebase origin main 2>/dev/null || { git rebase --abort 2>/dev/null; continue; }
        git push origin main 2>/dev/null && break
        sleep 2
    done
fi

flock -u 9
