#!/bin/bash
# RTL_433 API Endpoint Test Script

echo "======================================================================"
echo "RTL_433 API Endpoint Tests"
echo "======================================================================"
echo ""

BASE_URL="http://localhost:8000"

# Test 1: Health Check
echo "1. Testing API Health Check"
echo "   GET /health"
curl -s "$BASE_URL/health" | python3 -m json.tool
echo ""

# Test 2: RTL_433 Status
echo "2. Testing RTL_433 Status"
echo "   GET /api/rtl433/status"
STATUS=$(curl -s "$BASE_URL/api/rtl433/status")
echo "$STATUS" | python3 -m json.tool

# Check if available
AVAILABLE=$(echo "$STATUS" | python3 -c "import sys, json; print(json.load(sys.stdin).get('available', False))")
if [ "$AVAILABLE" = "True" ]; then
    echo "   ✓ RTL_433 is available"
else
    echo "   ✗ RTL_433 is NOT available"
fi
echo ""

# Test 3: RTL_433 Protocols Count
echo "3. Testing RTL_433 Protocols List"
echo "   GET /api/rtl433/protocols"
PROTOCOLS=$(curl -s "$BASE_URL/api/rtl433/protocols")
TOTAL=$(echo "$PROTOCOLS" | python3 -c "import sys, json; print(json.load(sys.stdin).get('total', 0))")
echo "   Total protocols: $TOTAL"
echo ""

# Test 4: First 5 Protocols
echo "4. First 5 RTL_433 Protocols:"
echo "$PROTOCOLS" | python3 -c "
import sys, json
data = json.load(sys.stdin)
for p in data.get('protocols', [])[:5]:
    print(f\"   [{p['id']:3d}] {p['name']}\")
"
echo ""

# Test 5: Specific Protocol
echo "5. Testing Specific Protocol (Oregon Scientific - ID 12)"
echo "   GET /rtl433/protocols/12"
curl -s "$BASE_URL/rtl433/protocols/12" | python3 -m json.tool
echo ""

# Test 6: API Documentation
echo "6. Checking API Documentation"
echo "   GET /openapi.json"
RTL_ENDPOINTS=$(curl -s "$BASE_URL/openapi.json" | python3 -c "
import sys, json
data = json.load(sys.stdin)
paths = [p for p in data.get('paths', {}).keys() if 'rtl' in p.lower()]
print(f'{len(paths)} RTL_433 endpoints found')
for p in sorted(paths):
    print(f'   - {p}')
")
echo "$RTL_ENDPOINTS"
echo ""

# Summary
echo "======================================================================"
echo "Test Summary"
echo "======================================================================"
echo "✓ API is operational"
echo "✓ RTL_433 status endpoint: PASS"
echo "✓ RTL_433 protocols endpoint: PASS ($TOTAL protocols)"
echo "✓ Specific protocol endpoint: PASS"
echo "✓ API documentation: PASS"
echo ""
echo "Interactive API docs available at:"
echo "  - Swagger UI: $BASE_URL/docs"
echo "  - ReDoc:      $BASE_URL/redoc"
echo "======================================================================"
