#!/bin/bash

echo "=========================================="
echo "Momentry Core API 測試腳本"
echo "=========================================="
echo ""

# 顏色定義
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 測試 1: Momentry Core 搜尋
echo -e "${YELLOW}測試 1: Momentry Core 搜尋 API${NC}"
echo "URL: http://localhost:3002/api/v1/n8n/search"
echo ""
RESPONSE=$(curl -s -X POST http://localhost:3002/api/v1/n8n/search \
	-H "Content-Type: application/json" \
	-d '{"query":"charade","limit":2}')

if echo "$RESPONSE" | grep -q '"hits"'; then
	echo -e "${GREEN}✅ 成功!${NC}"
	echo "$RESPONSE" | python3 -m json.tool | grep -E '"query"|"count"' | head -3
	echo ""
	echo "前 2 個結果:"
	echo "$RESPONSE" | python3 -c "
import sys, json
data = json.load(sys.stdin)
for i, hit in enumerate(data.get('hits', [])[:2]):
    print(f\"  [{i+1}] {hit.get('text', '')[:50]}...\")
    print(f\"      時間: {hit.get('start')}s - {hit.get('end')}s\")
    print(f\"      影片: {hit.get('title')}\")
"
else
	echo -e "${RED}❌ 失敗${NC}"
	echo "$RESPONSE"
fi
echo ""

# 測試 2: 列出影片
echo -e "${YELLOW}測試 2: 列出所有影片${NC}"
echo "URL: http://localhost:3002/api/v1/videos"
echo ""
RESPONSE=$(curl -s http://localhost:3002/api/v1/videos)

if echo "$RESPONSE" | grep -q '"videos"'; then
	echo -e "${GREEN}✅ 成功!${NC}"
	echo "$RESPONSE" | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(f\"找到 {len(data.get('videos', []))} 個影片:\")
for v in data.get('videos', []):
    print(f\"  - {v.get('file_name')} (UUID: {v.get('uuid')[:8]}...)\")
"
else
	echo -e "${RED}❌ 失敗${NC}"
fi
echo ""

# 測試 3: n8n Webhook (Test Mode)
echo -e "${YELLOW}測試 3: n8n Webhook (Test Mode)${NC}"
echo "URL: http://localhost:5678/webhook-test/video-rag-mcp"
echo ""
echo "⚠️  注意: 請先在 n8n UI 中點擊 'Execute workflow' 按鈕"
echo ""

RESPONSE=$(curl -s -X POST http://localhost:5678/webhook-test/video-rag-mcp \
	-H "Content-Type: application/json" \
	-d '{"query":"charade","limit":2}')

if echo "$RESPONSE" | grep -q '"success": true'; then
	echo -e "${GREEN}✅ Webhook 測試成功!${NC}"
	echo "$RESPONSE" | python3 -c "
import sys, json
data = json.load(sys.stdin)
print(f\"查詢: {data.get('query')}\")
print(f\"找到: {data.get('totalFound')} 個結果\")
print(f\"Context 長度: {len(data.get('context', ''))} 字元\")
"
elif echo "$RESPONSE" | grep -q '404'; then
	echo -e "${RED}❌ Webhook 未找到${NC}"
	echo "請在 n8n UI 中:"
	echo "  1. 開啟 'Momentry Video RAG MCP' 工作流程"
	echo "  2. 點擊 'Execute workflow' 按鈕"
	echo "  3. 30 秒內再次執行此腳本"
else
	echo -e "${RED}❌ 錯誤${NC}"
	echo "$RESPONSE" | python3 -m json.tool 2>/dev/null || echo "$RESPONSE"
fi
echo ""

echo "=========================================="
echo "測試完成!"
echo "=========================================="
echo ""
echo "快速參考:"
echo "  Momentry API: http://localhost:3002/api/v1"
echo "  n8n UI:       https://n8n.momentry.ddns.net"
echo "  Webhook Test: http://localhost:5678/webhook-test/video-rag-mcp"
