#!/bin/bash

# Test Momentry Video RAG MCP Workflow
# Usage: ./test_workflow.sh [query] [limit] [uuid]

N8N_URL="http://localhost:5678"
WEBHOOK_PATH="webhook-test/video-rag-mcp"

echo "⚠️  注意：使用 Test Webhook URL"
echo "（生產環境 Webhook 需要工作流程手動激活後才能使用）"
echo ""

# Default values
QUERY="${1:-charade}"
LIMIT="${2:-3}"
UUID="${3:-}"

echo "=========================================="
echo "Testing Video RAG Workflow"
echo "=========================================="
echo "Query: $QUERY"
echo "Limit: $LIMIT"
if [ -n "$UUID" ]; then
    echo "UUID: $UUID"
fi
echo ""

# Build JSON payload
if [ -n "$UUID" ]; then
    PAYLOAD=$(cat <<JSON
{
    "query": "$QUERY",
    "limit": $LIMIT,
    "uuid": "$UUID"
}
JSON
)
else
    PAYLOAD=$(cat <<JSON
{
    "query": "$QUERY",
    "limit": $LIMIT
}
JSON
)
fi

echo "Request:"
echo "$PAYLOAD" | python3 -m json.tool 2>/dev/null || echo "$PAYLOAD"
echo ""
echo "=========================================="
echo "Response:"
echo "=========================================="
echo "URL: ${N8N_URL}/${WEBHOOK_PATH}"
echo ""

# Make the request
RESPONSE=$(curl -s -X POST "${N8N_URL}/${WEBHOOK_PATH}" \
    -H "Content-Type: application/json" \
    -d "$PAYLOAD")

# Format and display response
echo "$RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$RESPONSE"

echo ""
echo "=========================================="

# Check if successful
if echo "$RESPONSE" | grep -q '"success": true'; then
    echo "✅ Test PASSED"
    
    # Extract and display summary
    echo ""
    echo "Summary:"
    echo "$RESPONSE" | python3 -c "
import sys, json
data = json.load(sys.stdin)
if data.get('success'):
    print(f\"  Query: {data.get('query', 'N/A')}\")
    print(f\"  Total Found: {data.get('totalFound', 0)}\")
    results = data.get('results', [])
    print(f\"  Results Count: {len(results)}\")
    print()
    print('  Top Results:')
    for r in results[:3]:
        print(f\"    [{r.get('index')}] {r.get('title', 'Unknown')}\")
        text = r.get('text', '')[:50]
        print(f\"        Text: {text}...\")
        print(f\"        Time: {r.get('startTime')}s - {r.get('endTime')}s\")
        print(f\"        Relevance: {r.get('relevance')}\")
        print()
" 2>/dev/null || true
elif echo "$RESPONSE" | grep -q '"code": 404'; then
    echo "❌ Webhook not found"
    echo ""
    echo "可能的解決方案："
    echo "  1. 在 n8n UI 中開啟工作流程: https://n8n.momentry.ddns.net"
    echo "  2. 點擊右上角的 'Active' 開關"
    echo "  3. 或者使用 test webhook: webhook-test/video-rag-mcp"
else
    echo "❌ Test FAILED or no results found"
fi

echo "=========================================="
