#!/bin/bash
# One-shot launcher for the scheduled Brain-OS-Audit (KAR-859, ordered 2026-07-06).
# Fires 2026-07-07 after the weekly Fable budget reset. It does NOT run the audit
# itself — it (1) notifies Kais and (2) injects a trigger into the live `aria` tmux
# session. The Aria session then performs the rigorous, repeated Fable-5 verification
# (per EXECUTION-SPEC.md pre-flight) and runs the full audit with all tools.
#
# Rationale: the shell can't do deep reasoning / file edits / Linear / Fable-gating;
# the Claude-Code session can. So the launcher stays trivial+reliable and delegates.
set -uo pipefail
LOG=/root/aria/logs/brain-os-audit-launch.log
mkdir -p /root/aria/logs
log(){ echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*" >> "$LOG"; }

# --- Telegram config ---
TOKEN=$(grep -E '^TELEGRAM_BOT_TOKEN=' /root/aria/.env 2>/dev/null | head -1 | cut -d= -f2- | tr -d '"')
CHAT=$(grep -E '^TELEGRAM_CHAT_ID=' /root/aria/.env 2>/dev/null | head -1 | cut -d= -f2- | tr -d '"')
[ -z "${CHAT:-}" ] && CHAT=1164395546   # Kais fallback
tg(){ [ -n "${TOKEN:-}" ] && curl -s -m 10 "https://api.telegram.org/bot${TOKEN}/sendMessage" \
      --data-urlencode "chat_id=${CHAT}" --data-urlencode "text=$1" >/dev/null 2>&1; }

log "=== launcher start ==="

# --- coarse Fable check (the session re-verifies rigorously) ---
JSONL=$(ls -t /root/.claude/projects/-/*.jsonl 2>/dev/null | head -1)
MODEL_TAIL=$(grep -o '"model":"[^"]*"' "$JSONL" 2>/dev/null | tail -5 | tr '\n' ' ')
log "latest jsonl: $JSONL | recent models: $MODEL_TAIL"

if ! tmux has-session -t aria 2>/dev/null; then
  log "ERROR: tmux session 'aria' not found — cannot inject."
  tg "⚠️ Brain-OS-Audit (KAR-859): geplanter Start, aber die aria-tmux-Session läuft nicht. Bitte Aria-Session starten, dann sage 'starte KAR-859'."
  exit 1
fi

TRIGGER="[SCHEDULED AUTONOMOUS RUN — KAR-859] Fuehre jetzt den Brain-OS-Audit vollstaendig autonom aus. Schritt 1: Lies /root/aria/brain/01-Projekte/aria-brain-os-audit/EXECUTION-SPEC.md KOMPLETT. Schritt 2: Fuehre das Fable-5-Pre-Flight aus (config + LIVE-Transcript-Modell pruefen, nicht das Identity-Feld) und verifiziere mehrfach dass Fable 5 laeuft. Wenn Fable NICHT laeuft: pausiere und frag Kais per Telegram (warten / Paid-Credits / auf Opus fahren) — entscheide das NICHT selbst. Wenn Fable laeuft: setze den kompletten Audit (9 Deliverables, KARs deduped, sichere Doc-Edits auf Working-Branch) autonom um und liefere den deutschen Report per Telegram."

# inject the trigger as user input into the live Claude Code REPL
if [ "${DRY_RUN:-0}" = "1" ]; then
  log "DRY_RUN=1 — skipping send-keys injection; would inject trigger now."
  tg "🧪 Brain-OS-Audit Launcher DRY-RUN ok (KAR-859). tmux+Fable-Check+Telegram funktionieren. Echter Start morgen 10:30 UTC. Letzte Modelle: ${MODEL_TAIL}"
  log "=== launcher DRY-RUN done ==="
  exit 0
fi

tmux send-keys -t aria "$TRIGGER" 2>>"$LOG"
sleep 2
tmux send-keys -t aria Enter 2>>"$LOG"
RC=$?
log "injected trigger into tmux aria (send-keys rc=$RC)"

tg "🌅 Brain-OS-Audit (KAR-859) planmaessig gestartet. Aria verifiziert jetzt Fable 5 und laeuft den Audit autonom. Falls Fable nicht verfuegbar, meldet sich Aria mit einer Rueckfrage. Letzte Modelle im Transcript: ${MODEL_TAIL}"
log "=== launcher done ==="
