#!/bin/bash

# Test script for posting large events (>4KB) to test partial write handling
# Uses nak to properly sign events with large content

RELAY_URL="ws://localhost:8888"

# Check if nak is installed
if ! command -v nak &> /dev/null; then
    echo "Error: nak is not installed. Install with: go install github.com/fiatjaf/nak@latest"
    exit 1
fi

# Generate a test private key if not set
if [ -z "$NOSTR_PRIVATE_KEY" ]; then
    echo "Generating temporary test key..."
    export NOSTR_PRIVATE_KEY=$(nak key generate)
fi

echo "=== Large Event Test ==="
echo "Testing partial write handling with events >4KB"
echo "Relay: $RELAY_URL"
echo ""

# Test 1: 5KB event
echo "Test 1: Posting 5KB event..."
CONTENT_5KB=$(python3 -c "print('A' * 5000)")
echo "$CONTENT_5KB" | nak event -k 1 --content - $RELAY_URL
sleep 1

# Test 2: 10KB event
echo ""
echo "Test 2: Posting 10KB event..."
CONTENT_10KB=$(python3 -c "print('B' * 10000)")
echo "$CONTENT_10KB" | nak event -k 1 --content - $RELAY_URL
sleep 1

# Test 3: 20KB event
echo ""
echo "Test 3: Posting 20KB event..."
CONTENT_20KB=$(python3 -c "print('C' * 20000)")
echo "$CONTENT_20KB" | nak event -k 1 --content - $RELAY_URL
sleep 1

# Test 4: 50KB event (very large)
echo ""
echo "Test 4: Posting 50KB event..."
CONTENT_50KB=$(python3 -c "print('D' * 50000)")
echo "$CONTENT_50KB" | nak event -k 1 --content - $RELAY_URL

echo ""
echo "=== Test Complete ==="
echo ""
echo "Check relay.log for:"
echo "  - 'Queued partial write' messages (indicates buffering is working)"
echo "  - 'write completed' messages (indicates retry succeeded)"
echo "  - No 'Invalid frame header' errors"
echo ""
echo "To view logs in real-time:"
echo "  tail -f relay.log | grep -E '(partial|write completed|Invalid frame)'"
echo ""
echo "To check if events were stored:"
echo "  sqlite3 build/*.db 'SELECT id, length(content) as content_size FROM events ORDER BY created_at DESC LIMIT 4;'"