#!/bin/bash
# API 測試驗證腳本

set -e

echo "================================================"
echo "人臉識別 API 測試驗證"
echo "================================================"

# 創建測試圖像
echo -e "\n1. 創建測試圖像..."
cat >/tmp/create_test_image.py <<'EOF'
import cv2
import numpy as np

# 創建測試圖像
img = np.zeros((480, 640, 3), dtype=np.uint8)
img.fill(200)  # 灰色背景

# 添加一個簡單的"人臉"（圓形）
cv2.circle(img, (320, 240), 100, (255, 200, 150), -1)  # 臉部
cv2.circle(img, (280, 200), 20, (0, 0, 0), -1)  # 左眼
cv2.circle(img, (360, 200), 20, (0, 0, 0), -1)  # 右眼
cv2.ellipse(img, (320, 280), (40, 20), 0, 0, 360, (0, 0, 0), -1)  # 嘴巴

cv2.imwrite('/tmp/test_face.jpg', img)
print("測試圖像已創建: /tmp/test_face.jpg")
EOF

python3 /tmp/create_test_image.py

# 檢查服務器是否運行
echo -e "\n2. 檢查服務器狀態..."
if curl -s http://localhost:3002/health >/dev/null; then
	echo "✅ 服務器正在運行"
else
	echo "⚠️  服務器未運行，請先啟動: cargo run -- server"
	echo "正在後台啟動服務器..."
	cd /Users/accusys/momentry_core_0.1
	cargo run -- server >/tmp/momentry_server.log 2>&1 &
	SERVER_PID=$!
	echo "服務器已啟動 (PID: $SERVER_PID)"
	sleep 5 # 等待服務器啟動
fi

# 測試健康檢查端點
echo -e "\n3. 測試健康檢查端點..."
curl -s http://localhost:3002/health | jq . || echo "響應: $(curl -s http://localhost:3002/health)"

# 測試人臉註冊 API
echo -e "\n4. 測試人臉註冊 API..."
if [ -f "/tmp/test_face.jpg" ]; then
	echo "發送註冊請求..."
	RESPONSE=$(curl -s -X POST http://localhost:3002/api/v1/face/register \
		-F "image=@/tmp/test_face.jpg" \
		-F "name=Test Person" \
		-F "metadata={\"test\": true, \"source\": \"api_test\"}")

	echo "響應:"
	echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"

	# 提取 face_id
	FACE_ID=$(echo "$RESPONSE" | grep -o '"face_id":"[^"]*"' | cut -d'"' -f4)
	if [ -n "$FACE_ID" ]; then
		echo "✅ 註冊成功，Face ID: $FACE_ID"
		echo "$FACE_ID" >/tmp/test_face_id.txt
	else
		echo "❌ 註冊失敗"
	fi
else
	echo "❌ 測試圖像不存在"
fi

# 測試列出人臉 API
echo -e "\n5. 測試列出人臉 API..."
echo "發送列表請求..."
RESPONSE=$(curl -s -X GET "http://localhost:3002/api/v1/face/list?limit=10")
echo "響應:"
echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"

# 測試搜索人臉 API（如果註冊成功）
echo -e "\n6. 測試搜索人臉 API..."
if [ -n "$FACE_ID" ]; then
	echo "創建測試嵌入向量..."
	cat >/tmp/create_test_embedding.py <<'EOF'
import numpy as np
import json

# 創建一個測試嵌入向量（512維）
embedding = np.random.randn(512).tolist()

# 保存為 JSON
with open('/tmp/test_embedding.json', 'w') as f:
    json.dump({
        "embedding": embedding,
        "similarity_threshold": 0.5,
        "limit": 5
    }, f)

print("測試嵌入向量已創建")
EOF

	python3 /tmp/create_test_embedding.py

	echo "發送搜索請求..."
	RESPONSE=$(curl -s -X POST http://localhost:3002/api/v1/face/search \
		-H "Content-Type: application/json" \
		-d @/tmp/test_embedding.json)

	echo "響應:"
	echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"
else
	echo "⚠️  跳過搜索測試（需要先註冊人臉）"
fi

# 測試獲取人臉詳情 API
echo -e "\n7. 測試獲取人臉詳情 API..."
if [ -n "$FACE_ID" ]; then
	echo "獲取人臉詳情: $FACE_ID"
	RESPONSE=$(curl -s -X GET "http://localhost:3002/api/v1/face/$FACE_ID")
	echo "響應:"
	echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"
else
	echo "⚠️  跳過詳情測試（需要先註冊人臉）"
fi

# 測試視頻處理 API
echo -e "\n8. 測試視頻處理 API..."
echo "發送視頻處理請求..."
RESPONSE=$(curl -s -X POST http://localhost:3002/api/v1/face/recognize \
	-H "Content-Type: application/json" \
	-d '{
        "video_uuid": "test_video_001",
        "enable_recognition": true,
        "enable_tracking": true,
        "enable_clustering": true
    }')

echo "響應:"
echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"

# 測試獲取處理結果 API
echo -e "\n9. 測試獲取處理結果 API..."
echo "獲取處理結果..."
RESPONSE=$(curl -s -X GET "http://localhost:3002/api/v1/face/results/test_video_001")
echo "響應:"
echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"

# 清理測試數據
echo -e "\n10. 清理測試數據..."
if [ -n "$FACE_ID" ]; then
	echo "刪除測試人臉: $FACE_ID"
	RESPONSE=$(curl -s -X DELETE "http://localhost:3002/api/v1/face/$FACE_ID")
	echo "刪除響應:"
	echo "$RESPONSE" | jq . 2>/dev/null || echo "$RESPONSE"
fi

# 清理文件
rm -f /tmp/test_face.jpg /tmp/test_embedding.json /tmp/test_face_id.txt /tmp/create_test_image.py /tmp/create_test_embedding.py

echo -e "\n================================================"
echo "API 測試完成"
echo "================================================"

# 如果我們啟動了服務器，停止它
if [ -n "$SERVER_PID" ]; then
	echo "停止測試服務器 (PID: $SERVER_PID)..."
	kill $SERVER_PID 2>/dev/null || true
fi
