#!/usr/bin/env bash
# scripts/screenshot.sh — generate a README screenshot automatically
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"

INTERACTIVE=false
[[ "${1:-}" == "--interactive" ]] && INTERACTIVE=true

SESSION="qpq-screenshot"
SERVER_PORT=17123
SERVER_ADDR="127.0.0.1:${SERVER_PORT}"
DATA_DIR=$(mktemp -d)
CERT="${DATA_DIR}/server-cert.der"
KEY="${DATA_DIR}/server-key.der"
QPQ="./target/debug/qpq"
SERVER="./target/debug/qpq-server"
SLOG="${DATA_DIR}/server.log"

cleanup() {
    [[ -n "${SERVER_PID:-}" ]] && kill "$SERVER_PID" 2>/dev/null || true
    tmux kill-session -t "$SESSION" 2>/dev/null || true
    # Keep DATA_DIR for debugging
    echo "Data dir: $DATA_DIR"
}
trap cleanup EXIT

# ── Build ────────────────────────────────────────────────────────────────────
echo "Building binaries..."
cargo build --bin qpq --bin qpq-server 2>&1 | tail -1

# ── Start server ─────────────────────────────────────────────────────────────
echo "Starting server on ${SERVER_ADDR}..."
RUST_LOG=debug "$SERVER" \
    --allow-insecure-auth \
    --listen "$SERVER_ADDR" \
    --tls-cert "$CERT" \
    --tls-key "$KEY" \
    --data-dir "$DATA_DIR" \
    &>"$SLOG" &
SERVER_PID=$!

for _ in $(seq 1 30); do [[ -f "$CERT" ]] && break; sleep 0.2; done
if [[ ! -f "$CERT" ]]; then echo "ERROR: server did not start"; cat "$SLOG"; exit 1; fi
echo "Server ready (PID ${SERVER_PID})"

# ── tmux session ─────────────────────────────────────────────────────────────
tmux new-session -d -s "$SESSION" -x 114 -y 28

send_alice() { tmux send-keys -t "${SESSION}:0.0" "$1" Enter; }
send_bob()   { tmux send-keys -t "${SESSION}:0.1" "$1" Enter; }

# Start Alice (left pane)
tmux send-keys -t "$SESSION" \
    "RUST_LOG=debug $QPQ repl --username alice --password demopass1 --server $SERVER_ADDR --ca-cert $CERT --state ${DATA_DIR}/alice.bin 2>${DATA_DIR}/alice-debug.log" Enter

# Start Bob (right pane)
tmux split-window -h -t "$SESSION"
tmux send-keys -t "$SESSION" \
    "RUST_LOG=debug $QPQ repl --username bob --password demopass2 --server $SERVER_ADDR --ca-cert $CERT --state ${DATA_DIR}/bob.bin 2>${DATA_DIR}/bob-debug.log" Enter

tmux select-layout -t "$SESSION" even-horizontal
sleep 5

# Alice creates DM with Bob
send_alice "/dm bob"
sleep 4

# Wait for Bob's poller (8 seconds = 8 poll cycles)
echo "Waiting for Bob to poll Welcome..."
sleep 10

# Check Bob's list
send_bob "/list"
sleep 2

# Capture both panes
{
    echo "=== Alice ==="
    tmux capture-pane -t "${SESSION}:0.0" -p
    echo ""
    echo "=== Bob ==="
    tmux capture-pane -t "${SESSION}:0.1" -p
} > "${DATA_DIR}/capture.txt"

echo ""
cat "${DATA_DIR}/capture.txt"
echo ""
echo "Server log tail:"
tail -30 "$SLOG" 2>/dev/null || true
echo ""
echo "Debug logs in: $DATA_DIR"
echo "Check: $DATA_DIR/alice-debug.log and $DATA_DIR/bob-debug.log"
