#!/bin/bash
# Test script to verify Python TCK setup

set -e  # Exit on error

echo "=========================================="
echo "Python TCK Setup Verification"
echo "=========================================="
echo

# Check Python version
echo "1. Checking Python version..."
python3 --version
echo

# Check if maturin is installed
echo "2. Checking maturin..."
if ! command -v maturin &> /dev/null; then
    echo "❌ maturin not found, installing..."
    pip install maturin
else
    echo "✅ maturin found: $(maturin --version)"
fi
echo

# Build wheel
echo "3. Building Python wheel..."
export PYO3_USE_ABI3_FORWARD_COMPATIBILITY=1
maturin build --release --features python --out target/wheels
echo "✅ Wheel built"
echo

# Install wheel
echo "4. Installing wheel..."
python3 -m pip install --force-reinstall --break-system-packages target/wheels/*.whl 2>&1 | grep -E "(Successfully|Processing|Installing)"
echo "✅ Wheel installed"
echo

# Test import
echo "5. Testing import..."
python3 -c "import ocg; print(f'✅ ocg version {ocg.__version__}')"
echo

# Test basic functionality
echo "6. Testing basic query execution..."
python3 << 'EOF'
from ocg import Graph

g = Graph()
print(f"✅ Created graph: {g}")

g.execute("CREATE (n:Person {name: 'Alice', age: 30})")
print("✅ Created node")

result = g.execute("MATCH (n:Person) RETURN n.name AS name, n.age AS age")
print(f"✅ Query result: {result}")

if len(result) == 1 and result[0]['name'] == 'Alice' and result[0]['age'] == 30:
    print("✅ Result validation passed")
else:
    print(f"❌ Result validation failed: {result}")
    exit(1)
EOF
echo

# Check behave
echo "7. Checking behave..."
if ! python3 -c "import behave" 2>/dev/null; then
    echo "❌ behave not found, installing..."
    pip install behave>=1.2.6
else
    echo "✅ behave found"
fi
echo

# Count feature files
echo "8. Checking TCK feature files..."
FEATURE_COUNT=$(find tests/tck/features -name "*.feature" -type f | wc -l | tr -d ' ')
echo "✅ Found $FEATURE_COUNT feature files"
echo

# Check step definitions
echo "9. Checking step definitions..."
if [ -f "tests/tck/features/steps/cypher_steps.py" ]; then
    STEP_COUNT=$(grep -c "^@given\\|^@when\\|^@then\\|^@step" tests/tck/features/steps/cypher_steps.py)
    echo "✅ Found $STEP_COUNT step definitions"
else
    echo "❌ Step definitions not found"
    exit 1
fi
echo

# Run a simple feature test (dry run)
echo "10. Testing behave dry run..."
cd tests/tck
python3 -m behave --dry-run features/expressions/boolean/Boolean1.feature 2>&1 | head -20 || true
cd ../..
echo

echo "=========================================="
echo "✅ Setup verification complete!"
echo "=========================================="
echo
echo "To run Python TCK tests:"
echo "  cd tests/tck"
echo "  behave"
echo
echo "Or run specific feature:"
echo "  behave features/clauses/match/Match1.feature"
echo
