#!/bin/bash
# Sync tests to ward tester (standalone, no coupling)
# Configure paths via environment variables
#
# Usage:
#   # Set env vars
#   export TEST_SOURCE_PATH=~/wdir/ama/amar_django_back/tests/contracts
#   export WARD_TESTS_PATH=~/wdir/ama/soleprint/ward/tools/tester/tests
#
#   # Run sync
#   ./sync-tests-local.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SILENT_FAIL="${SILENT_FAIL:-false}"

# Load from .env.sync if it exists
if [ -f "$SCRIPT_DIR/.env.sync" ]; then
    source "$SCRIPT_DIR/.env.sync"
fi

# Check required vars
if [ -z "$TEST_SOURCE_PATH" ]; then
    if [ "$SILENT_FAIL" = "true" ]; then
        exit 0
    fi
    echo "Error: TEST_SOURCE_PATH not set"
    echo ""
    echo "Set environment variables:"
    echo "  export TEST_SOURCE_PATH=~/wdir/ama/amar_django_back/tests/contracts"
    echo "  export WARD_TESTS_PATH=~/wdir/ama/soleprint/ward/tools/tester/tests"
    echo ""
    echo "Or create ctrl/.env.sync with these variables"
    exit 1
fi

if [ -z "$WARD_TESTS_PATH" ]; then
    if [ "$SILENT_FAIL" = "true" ]; then
        exit 0
    fi
    echo "Error: WARD_TESTS_PATH not set"
    exit 1
fi

# Expand paths
SOURCE=$(eval echo "$TEST_SOURCE_PATH")
TARGET=$(eval echo "$WARD_TESTS_PATH")

if [ ! -d "$SOURCE" ]; then
    if [ "$SILENT_FAIL" = "true" ]; then
        exit 0
    fi
    echo "Error: Source directory not found: $SOURCE"
    exit 1
fi

echo "=== Syncing Contract Tests ==="
echo ""
echo "Source: $SOURCE"
echo "Target: $TARGET"
echo ""

# Create target if it doesn't exist
mkdir -p "$TARGET"

# Sync tests (use shared exclude file)
rsync -av --delete \
    --exclude-from="$SCRIPT_DIR/.exclude" \
    "$SOURCE/" \
    "$TARGET/"

echo ""
echo "[OK] Tests synced successfully"
echo ""
echo "Changes are immediately visible in Docker (volume mount)"
echo "Just refresh your browser - no restart needed!"
echo ""

# Count test files
TEST_COUNT=$(find "$TARGET" -name "test_*.py" | wc -l)
echo "Total test files: $TEST_COUNT"
echo ""
