#!/bin/bash
# Validate VRL files before deployment
# Usage: ./validate.sh [vrl_file]

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
VRL_FILE="${1:-$SCRIPT_DIR/detect_and_parse.vrl}"
TEST_FILE="$SCRIPT_DIR/test_logs.jsonl"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "=========================================="
echo "Vector VRL Validator"
echo "=========================================="
echo ""

# Check if vector is installed
if ! command -v vector &> /dev/null; then
    echo -e "${YELLOW}Vector not found locally, using Docker...${NC}"
    USE_DOCKER=true
else
    USE_DOCKER=false
fi

run_vrl() {
    local input="$1"
    local program="$2"

    if [ "$USE_DOCKER" = true ]; then
        echo "$input" | docker run --rm -i -v "$SCRIPT_DIR:/vrl" timberio/vector:latest-alpine vrl --program "$program"
    else
        echo "$input" | vector vrl --program "$program"
    fi
}

echo "1. Validating VRL syntax..."
echo "   File: $(basename $VRL_FILE)"
echo ""

# Validate syntax
if [ "$USE_DOCKER" = true ]; then
    PROGRAM_PATH="/vrl/$(basename $VRL_FILE)"
else
    PROGRAM_PATH="$VRL_FILE"
fi

if run_vrl '{"message": "test"}' "$PROGRAM_PATH" > /dev/null 2>&1; then
    echo -e "   ${GREEN}✓ Syntax OK${NC}"
else
    echo -e "   ${RED}✗ Syntax Error${NC}"
    echo ""
    echo "Error details:"
    run_vrl '{"message": "test"}' "$PROGRAM_PATH" 2>&1
    exit 1
fi

echo ""
echo "2. Running test cases..."
echo ""

PASS=0
FAIL=0

while IFS= read -r line || [ -n "$line" ]; do
    [ -z "$line" ] && continue

    result=$(run_vrl "$line" "$PROGRAM_PATH" 2>&1)
    exit_code=$?

    if [ $exit_code -eq 0 ]; then
        format=$(echo "$result" | grep -o '"log_format":"[^"]*"' | cut -d'"' -f4)
        level=$(echo "$result" | grep -o '"level":"[^"]*"' | cut -d'"' -f4)
        msg=$(echo "$line" | sed 's/.*"message":"\([^"]*\)".*/\1/' | head -c 60)

        printf "   ${GREEN}✓${NC} %-15s level=%-8s %s...\n" "format=$format" "$level" "$msg"
        ((PASS++))
    else
        echo -e "   ${RED}✗ FAILED${NC}"
        echo "     input: $line"
        echo "     error: $result"
        ((FAIL++))
    fi
done < "$TEST_FILE"

echo ""
echo "=========================================="
echo "Results: $PASS passed, $FAIL failed"
echo "=========================================="

if [ $FAIL -gt 0 ]; then
    exit 1
fi

echo ""
echo -e "${GREEN}All tests passed!${NC}"
