#!/usr/bin/env bash
# save_scrollback.sh — capture each agent's tmux pane to logs/<name>_latest.log
# and push to GitHub. Intended to run daily via cron.
#
# Cron entry (midnight every day):
#   0 0 * * * bash /data/cameron/agents_stuff/shared/save_scrollback.sh \
#               >> /data/cameron/agents_stuff/logs/cron.log 2>&1
#
# Behavior:
#   - reads the agent list from config.yaml (so adding/removing an agent doesn't
#     require editing this script)
#   - captures last MAX_LINES lines of each agent's tmux pane
#   - overwrites logs/<name>_latest.log (single file per agent — no rotation
#     bloat in git history)
#   - commits + pushes if anything changed; silent if nothing changed
#
# Manual run:
#   bash /data/cameron/agents_stuff/shared/save_scrollback.sh
#   bash /data/cameron/agents_stuff/shared/save_scrollback.sh --no-push

set -euo pipefail

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
CONFIG="$REPO_ROOT/config.yaml"
LOGS_DIR="$REPO_ROOT/logs"
MAX_LINES="${MAX_LINES:-5000}"
SESSION="$(python3 -c "import yaml; print(yaml.safe_load(open('$CONFIG')).get('session', 'agents'))")"

PUSH=1
[[ "${1:-}" == "--no-push" ]] && PUSH=0

mkdir -p "$LOGS_DIR"

TIMESTAMP="$(date -Iseconds)"
echo "[$TIMESTAMP] Starting scrollback capture"

# Read agent + service names from config.yaml
mapfile -t WINDOWS < <(python3 - <<PY
import yaml
cfg = yaml.safe_load(open("$CONFIG"))
for n in cfg.get("agents", {}): print(n)
for n in cfg.get("services", {}): print(n)
PY
)

if ! tmux has-session -t "$SESSION" 2>/dev/null; then
    echo "[$TIMESTAMP] tmux session '$SESSION' not running — nothing to capture"
    exit 0
fi

CAPTURED=0
SKIPPED=0
for name in "${WINDOWS[@]}"; do
    if tmux list-windows -t "$SESSION" -F "#{window_name}" 2>/dev/null | grep -qx "$name"; then
        # -S -$MAX_LINES grabs the last MAX_LINES lines of scrollback + visible pane
        tmux capture-pane -t "${SESSION}:${name}" -p -S "-${MAX_LINES}" \
            > "$LOGS_DIR/${name}_latest.log" 2>/dev/null \
            && CAPTURED=$((CAPTURED+1)) \
            || { echo "  ! capture failed for $name"; SKIPPED=$((SKIPPED+1)); }
    else
        SKIPPED=$((SKIPPED+1))
    fi
done

echo "[$TIMESTAMP] Captured $CAPTURED, skipped $SKIPPED"

# --- git commit + push -----------------------------------------------------
cd "$REPO_ROOT"

if ! git rev-parse --git-dir >/dev/null 2>&1; then
    echo "[$TIMESTAMP] Not a git repo yet — skipping push"
    exit 0
fi

git add logs/
if git diff --cached --quiet; then
    echo "[$TIMESTAMP] No log changes to commit"
    exit 0
fi

git -c user.email="cron@$(hostname)" -c user.name="agents-cron" \
    commit -m "scrollback snapshot $TIMESTAMP" >/dev/null

if [[ $PUSH -eq 1 ]]; then
    if git push origin HEAD 2>&1; then
        echo "[$TIMESTAMP] Pushed scrollback snapshot"
    else
        echo "[$TIMESTAMP] Push failed (will retry next run)"
        exit 1
    fi
else
    echo "[$TIMESTAMP] Committed locally (--no-push)"
fi
