#!/usr/bin/env bash
# aria-reels-batch-watch.sh
# Cron-friendly Reels-Voll-Watch-Batch.
# Pro Aufruf: 1 Reel aus Queue ziehen, transkribieren, Result parken.
# Bei IG-Rate-Limit: Reel bleibt in Queue, Cron probiert beim naechsten Tick.
# Wenn Queue leer: Telegram-Notification + minimale Brain-Summary.
#
# Usage (manual): bash aria-reels-batch-watch.sh
# Usage (cron):   systemd-Timer aria-reels-batch.timer alle 20 Min
set -euo pipefail

QUEUE=/root/aria/state/reels-queue.txt
DONE=/root/aria/state/reels-done.txt
INBOX=/root/aria/brain/00-Inbox/Videos
LOG=/var/log/aria-reels-batch.log
TG_CHAT="1164395546"

mkdir -p "$(dirname "$QUEUE")" "$INBOX"
touch "$QUEUE" "$DONE"

# Helper: log with timestamp
say() { echo "[$(date -Iseconds)] $*" >> "$LOG"; }

# Skip wenn Queue leer — nur wenn vorher noch Reels in Queue waren,
# einmalig "Batch fertig" senden.
if [[ ! -s "$QUEUE" ]]; then
  if [[ -f /root/aria/state/reels-batch-complete-sent.flag ]]; then
    say "queue empty, completion already sent — exit"
    exit 0
  fi

  done_count=$(grep -c . "$DONE" 2>/dev/null || echo 0)
  if (( done_count > 0 )); then
    # Telegram-Notify nur EINMAL
    if [[ -x /root/aria/scripts/aria-telegram-send.sh ]]; then
      /root/aria/scripts/aria-telegram-send.sh "$TG_CHAT" "Reels-Batch fertig: $done_count Transkripte in $INBOX. Brain-Synthese in naechster Aria-Session."
    elif command -v curl >/dev/null 2>&1; then
      TG_TOKEN=$(grep -E '^TG_TOKEN=' /root/.claude/channels/telegram/.env 2>/dev/null | cut -d= -f2- || echo "")
      if [[ -n "$TG_TOKEN" ]]; then
        curl -s -X POST "https://api.telegram.org/bot${TG_TOKEN}/sendMessage" \
          -d "chat_id=${TG_CHAT}" \
          -d "text=Reels-Batch fertig: ${done_count} Transkripte in ${INBOX}. Brain-Synthese in naechster Aria-Session." \
          >/dev/null 2>&1 || true
      fi
    fi
    touch /root/aria/state/reels-batch-complete-sent.flag
    say "queue empty after $done_count reels — sent completion notice"
  fi
  exit 0
fi

# Nimm die erste Zeile aus der Queue
URL=$(head -1 "$QUEUE")
if [[ -z "$URL" ]]; then
  exit 0
fi

REEL_ID=$(echo "$URL" | sed -E 's|.*/reel/([^/?]+).*|\1|')
say "trying $REEL_ID ($URL)"

# Ruf extract.sh auf, capture stdout (work-dir) + exit
WORK=$(bash /root/.claude/skills/claude-watch/scripts/extract.sh "$URL" 2>>"$LOG" || echo "")

if [[ -z "$WORK" || ! -d "$WORK" || ! -f "$WORK/transcript.txt" ]]; then
  say "FAIL $REEL_ID — likely rate-limit, leaving in queue"
  exit 0   # nicht-fail, Cron probiert spaeter
fi

# Success — parke Transcript + Frames-Pfad als Minimal-Note in Inbox
TRANSCRIPT_CHARS=$(wc -c < "$WORK/transcript.txt")
DUR=$(python3 -c "import json; print(int(json.load(open('$WORK/metadata.json'))['duration_seconds']))" 2>/dev/null || echo 0)
NOTE="$INBOX/reel-${REEL_ID}-pending-synthesis-$(date +%Y%m%d-%H%M).md"

cat > "$NOTE" <<EOF
---
title: "Reel ${REEL_ID} — Transcript pending Brain-Synthese"
type: inbox
tags: [reel, instagram, pending-synthesis, auto-batch]
date: $(date +%Y-%m-%d)
status: draft
source: ${URL}
duration_seconds: ${DUR}
transcript_chars: ${TRANSCRIPT_CHARS}
work_dir: ${WORK}
description: "Auto-Batch-Transcript via aria-reels-batch-watch.sh. Brain-Synthese steht aus (Aria in naechster Session)."
---

# Reel ${REEL_ID} — Auto-Batch Transcript

**Source:** ${URL}
**Dauer:** ${DUR} Sek
**Transcript:** ${TRANSCRIPT_CHARS} chars
**Frames:** ${WORK}/frames/frame_*.jpg

## Transcript

\`\`\`
$(cat "$WORK/transcript.txt")
\`\`\`

## TODO (Aria-Synthese in naechster Session)

- [ ] 7-Punkt-Praxisanalyse aus Transcript
- [ ] Frames lesen via Read-Tool
- [ ] Brain-Note in passendem Folder erstellen
- [ ] Diese Pending-Note loeschen wenn Synthese fertig
EOF

# Verschiebe URL aus Queue zu Done
tail -n +2 "$QUEUE" > "$QUEUE.tmp" && mv "$QUEUE.tmp" "$QUEUE"
echo "$URL" >> "$DONE"

say "OK $REEL_ID — transcript parked in $NOTE"
exit 0
