#!/bin/bash

set -e

echo "🧪 Testing Sayance Matrix Native Module Sync Functionality"
echo "========================================================="

# Get script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "📁 Working directory: $SCRIPT_DIR"

# Clean previous builds
echo "🧹 Cleaning previous builds..."
rm -rf build/
rm -rf target/
rm -rf ios/libsayance_matrix_native.a

# Build Rust library with debug info
echo "🦀 Building Rust library with logging..."
cd rust
RUST_LOG=debug cargo build --release
echo "✅ Rust library built successfully"

# Generate UniFFI bindings
echo "🔧 Generating UniFFI bindings..."
cargo run --bin uniffi-bindgen generate src/matrix.udl --language swift --out-dir ../ios
echo "✅ iOS bindings generated"

if [[ "$OSTYPE" == "darwin"* ]]; then
    echo "🍎 Building iOS module..."
    cd ../ios
    ./build.sh
    cd ..
    echo "✅ iOS module built"
fi

cd ..

# Build TypeScript
echo "📜 Building TypeScript..."
npm run build 2>/dev/null || echo "⚠️ TypeScript build may have warnings"

echo ""
echo "✅ Build completed successfully!"
echo ""
echo "🔍 Debug Information:"
echo "To see Matrix SDK logs, set RUST_LOG=debug when running your app"
echo ""
echo "📋 Next Steps:"
echo "1. Run your React Native app with the updated module"
echo "2. Check console for detailed sync logs (both eprintln! and tracing logs)"
echo "3. Look for these key log messages:"
echo "   - '🚨 STARTING MATRIX SYNC SERVICE 🚨'"
echo "   - '✅ Client authenticated as: [user]'"
echo "   - '🏃 SyncService is running and syncing!'"
echo "   - '🔔 BROADCASTING SYNC STATE: SYNCING'"
echo ""
echo "🐛 Troubleshooting:"
echo "If sync still doesn't work:"
echo "1. Check that access token is valid"
echo "2. Verify homeserver is reachable"
echo "3. Check device authentication"
echo "4. Look for authentication/network errors in logs" 