#!/bin/bash

# Processor Test Suite for Momentry Core
# Tests all 9 contract-compliant processors

set -e

echo "=== Momentry Core Processor Test Suite ==="
echo "Testing all 9 contract-compliant processors"
echo ""

# Test video file
TEST_VIDEO="/Users/accusys/test_video/BigBuckBunny_320x180.mp4"
API_KEY="muser_29dd336ea8d44b9badbc650d503b0348_1774620247_b098ff47"
API_URL="http://localhost:3002"

# Check if video exists
if [ ! -f "$TEST_VIDEO" ]; then
	echo "❌ Test video not found: $TEST_VIDEO"
	exit 1
fi

echo "✅ Test video found: $(basename "$TEST_VIDEO")"
echo ""

# Test 1: Check API health
echo "Test 1: API Health Check"
if curl -s "$API_URL/health" | grep -q "ok"; then
	echo "✅ API is healthy"
else
	echo "❌ API health check failed"
	exit 1
fi
echo ""

# Test 2: Register video (creates job with all 9 processors)
echo "Test 2: Register Video"
REGISTER_RESPONSE=$(curl -s -X POST \
	-H "X-API-Key: $API_KEY" \
	-H "Content-Type: application/json" \
	-d "{\"file_path\": \"$TEST_VIDEO\"}" \
	"$API_URL/api/v1/videos/register" || true)

if echo "$REGISTER_RESPONSE" | grep -q "already_exists"; then
	echo "⚠️  Video already registered, checking existing job"
	# Get video UUID from database
	UUID=$(psql -U accusys -d momentry -h localhost -p 5432 -t -c "SELECT uuid FROM videos WHERE file_path = '$TEST_VIDEO' LIMIT 1;" | tr -d '[:space:]')
else
	UUID=$(echo "$REGISTER_RESPONSE" | jq -r '.uuid' 2>/dev/null || echo "")
fi

if [ -n "$UUID" ]; then
	echo "✅ Video UUID: $UUID"
else
	echo "❌ Failed to get video UUID"
	exit 1
fi
echo ""

# Test 3: Check job creation
echo "Test 3: Verify Job Creation"
JOB_INFO=$(psql -U accusys -d momentry -h localhost -p 5432 -t -c "SELECT id, status, processors, completed_processors FROM monitor_jobs WHERE uuid = '$UUID';")

if [ -n "$JOB_INFO" ]; then
	echo "✅ Job created successfully"
	echo "   Job info: $JOB_INFO"
else
	echo "❌ Job not found for UUID: $UUID"
	exit 1
fi
echo ""

# Test 4: Check worker is processing
echo "Test 4: Worker Status"
WORKER_PID=$(ps aux | grep "momentry worker" | grep -v grep | head -1 | awk '{print $2}')
if [ -n "$WORKER_PID" ]; then
	echo "✅ Worker running (PID: $WORKER_PID)"

	# Check worker logs for activity
	if tail -20 /Users/accusys/momentry/log/momentry_worker.log | grep -q "processing\|completed\|Processor"; then
		echo "✅ Worker is active"
	else
		echo "⚠️  Worker not showing recent activity"
	fi
else
	echo "❌ Worker not running"
fi
echo ""

# Test 5: Monitor processor progress
echo "Test 5: Processor Progress Monitoring"
echo "Waiting 30 seconds for processor progress..."
sleep 30

JOB_PROGRESS=$(psql -U accusys -d momentry -h localhost -p 5432 -t -c "SELECT processors, completed_processors, failed_processors FROM monitor_jobs WHERE uuid = '$UUID';")
echo "Job progress: $JOB_PROGRESS"
echo ""

# Test 6: Check individual processor results
echo "Test 6: Individual Processor Results"
PROCESSORS=("asr" "cut" "yolo" "ocr" "face" "pose" "asrx" "caption" "story")

for processor in "${PROCESSORS[@]}"; do
	COUNT=$(psql -U accusys -d momentry -h localhost -p 5432 -t -c "SELECT COUNT(*) FROM processor_results WHERE video_uuid = '$UUID' AND processor_type = '$processor';" | tr -d '[:space:]')
	if [ "$COUNT" -gt "0" ]; then
		echo "✅ $processor: $COUNT results"
	else
		echo "❌ $processor: No results yet"
	fi
done
echo ""

# Test 7: System status
echo "Test 7: System Status Check"
SYSTEM_STATUS=$(curl -s -H "X-API-Key: $API_KEY" "$API_URL/api/v1/system/status")
if echo "$SYSTEM_STATUS" | grep -q "worker"; then
	echo "✅ System status endpoint working"
else
	echo "⚠️  System status endpoint may require authentication"
fi
echo ""

echo "=== Test Summary ==="
echo "All 9 contract processors configured:"
echo "  - ASR (Automatic Speech Recognition)"
echo "  - CUT (Scene Detection)"
echo "  - YOLO (Object Detection)"
echo "  - OCR (Text Recognition)"
echo "  - Face (Face Detection)"
echo "  - Pose (Pose Estimation)"
echo "  - ASRX (Extended ASR)"
echo "  - Caption (Video Captioning)"
echo "  - Story (Narrative Generation)"
echo ""
echo "Note: Processor execution may take time depending on video length"
echo "Check /Users/accusys/momentry/log/momentry_worker.log for detailed progress"
