#!/bin/bash
# Momentry Core 部署乾運行腳本
# 顯示將執行的操作，不實際修改系統

set -e

# 參數處理
MODE="dry-run"
if [ "$1" = "--execute" ] || [ "$1" = "-e" ]; then
	MODE="execute"
	echo "⚠️  警告：將實際執行部署操作"
	read -p "確認要執行實際部署？(y/N): " CONFIRM
	if [ "$CONFIRM" != "y" ] && [ "$CONFIRM" != "Y" ]; then
		echo "取消部署"
		exit 0
	fi
else
	echo "🔍 乾運行模式：只顯示將執行的操作"
fi

echo "=== Momentry Core 部署流程 ==="
echo "模式: $MODE"
echo "時間: $(date)"
echo ""

# 1. 檢查當前狀態
echo "步驟 1: 檢查當前狀態"
echo "----------------------------------------"
echo "執行: ./scripts/deployment/safe/validate_environment.sh"
if [ "$MODE" = "execute" ]; then
	./scripts/deployment/safe/validate_environment.sh
else
	echo "   [乾運行] 將執行環境驗證"
fi
echo ""

# 2. 停止生產服務
echo "步驟 2: 停止生產服務"
echo "----------------------------------------"
STOP_CMD="sudo launchctl unload /Library/LaunchDaemons/com.momentry.api.plist"
echo "執行: $STOP_CMD"
if [ "$MODE" = "execute" ]; then
	echo "   🛑 正在停止服務..."
	if sudo launchctl unload /Library/LaunchDaemons/com.momentry.api.plist 2>/dev/null; then
		echo "   ✅ 服務已停止"
	else
		echo "   ⚠️  停止服務失敗（可能未運行）"
	fi
	sleep 2
else
	echo "   [乾運行] 將停止生產服務"
	echo "   注意: 需要 sudo 權限"
fi
echo ""

# 3. 備份當前二進制文件
echo "步驟 3: 備份當前二進制文件"
echo "----------------------------------------"
BACKUP_DIR="/Users/accusys/momentry/backup/$(date +%Y%m%d_%H%M%S)"
BACKUP_CMD="mkdir -p $BACKUP_DIR && cp /usr/local/bin/momentry $BACKUP_DIR/ 2>/dev/null || true"
echo "執行: $BACKUP_CMD"
if [ "$MODE" = "execute" ]; then
	echo "   💾 創建備份目錄..."
	mkdir -p "$BACKUP_DIR"
	if cp /usr/local/bin/momentry "$BACKUP_DIR/" 2>/dev/null; then
		echo "   ✅ 二進制文件已備份到: $BACKUP_DIR/"
	else
		echo "   ⚠️  無法備份二進制文件（可能不存在）"
	fi
else
	echo "   [乾運行] 將備份當前二進制文件到: $BACKUP_DIR"
fi
echo ""

# 4. 部署新二進制文件
echo "步驟 4: 部署新二進制文件"
echo "----------------------------------------"
SOURCE_BINARY="/Users/accusys/momentry_core_0.1/target/release/momentry"
TARGET_BINARY="/usr/local/bin/momentry"
DEPLOY_CMD="sudo cp $SOURCE_BINARY $TARGET_BINARY && sudo chmod +x $TARGET_BINARY"
echo "執行: $DEPLOY_CMD"
if [ "$MODE" = "execute" ]; then
	echo "   🚀 部署新版本..."
	if [ ! -f "$SOURCE_BINARY" ]; then
		echo "   ❌ 源二進制文件不存在: $SOURCE_BINARY"
		echo "   請先執行: cargo build --release --bin momentry"
		exit 1
	fi

	if sudo cp "$SOURCE_BINARY" "$TARGET_BINARY"; then
		sudo chmod +x "$TARGET_BINARY"
		echo "   ✅ 二進制文件已部署到: $TARGET_BINARY"
		echo "   文件大小: $(ls -lh "$TARGET_BINARY" | awk '{print $5}')"
	else
		echo "   ❌ 部署失敗"
		exit 1
	fi
else
	echo "   [乾運行] 將複製: $SOURCE_BINARY -> $TARGET_BINARY"
	echo "   注意: 需要 sudo 權限"
fi
echo ""

# 5. 啟動生產服務
echo "步驟 5: 啟動生產服務"
echo "----------------------------------------"
START_CMD="sudo launchctl load /Library/LaunchDaemons/com.momentry.api.plist"
echo "執行: $START_CMD"
if [ "$MODE" = "execute" ]; then
	echo "   🚀 啟動服務..."
	if sudo launchctl load /Library/LaunchDaemons/com.momentry.api.plist; then
		echo "   ✅ 服務已啟動"
	else
		echo "   ❌ 啟動服務失敗"
		exit 1
	fi
	sleep 3
else
	echo "   [乾運行] 將啟動生產服務"
	echo "   注意: 需要 sudo 權限"
fi
echo ""

# 6. 健康檢查
echo "步驟 6: 健康檢查"
echo "----------------------------------------"
HEALTH_CMD="curl -f -s -o /dev/null -w 'HTTP狀態碼: %{http_code}\\n響應時間: %{time_total}s\\n' --max-time 10 'http://localhost:3002/api/v1/health'"
echo "執行: $HEALTH_CMD"
if [ "$MODE" = "execute" ]; then
	echo "   🏥 執行健康檢查..."
	MAX_RETRIES=5
	RETRY_COUNT=0

	while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
		RETRY_COUNT=$((RETRY_COUNT + 1))
		echo "   嘗試 $RETRY_COUNT/$MAX_RETRIES..."

		if curl -f -s -o /dev/null -w "   HTTP狀態碼: %{http_code}\n   響應時間: %{time_total}s\n" --max-time 10 "http://localhost:3002/api/v1/health"; then
			echo "   ✅ 健康檢查通過"
			break
		else
			if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
				echo "   ❌ 健康檢查失敗，已達到最大重試次數"
				echo "   請檢查日誌: /Users/accusys/momentry/log/momentry_api.error.log"
				exit 1
			fi
			echo "   ⏳ 等待 3 秒後重試..."
			sleep 3
		fi
	done
else
	echo "   [乾運行] 將檢查生產服務健康狀態"
	echo "   預期: HTTP 200 OK"
fi
echo ""

# 7. 最終驗證
echo "步驟 7: 最終驗證"
echo "----------------------------------------"
VERIFY_CMD="ps aux | grep -E '[m]omentry.*server.*3002'"
echo "執行: $VERIFY_CMD"
if [ "$MODE" = "execute" ]; then
	echo "   🔍 驗證服務進程..."
	if ps aux | grep -E "[m]omentry.*server.*3002" >/dev/null; then
		echo "   ✅ 生產服務正在運行 (port 3002)"
	else
		echo "   ❌ 未找到生產服務進程"
		exit 1
	fi
else
	echo "   [乾運行] 將驗證服務進程是否存在"
fi
echo ""

echo "=== 部署完成 ==="
if [ "$MODE" = "execute" ]; then
	echo "🎉 實際部署已完成！"
	echo "📋 摘要:"
	echo "   - 生產服務已重啟"
	echo "   - 二進制文件已更新"
	echo "   - 健康檢查通過"
	echo "   - 備份保存在: $BACKUP_DIR"
	echo ""
	echo "🔗 測試鏈接:"
	echo "   健康檢查: curl http://localhost:3002/api/v1/health"
	echo "   搜索測試: curl -X POST http://localhost:3002/api/v1/n8n/search \\"
	echo "     -H 'X-API-Key: YOUR_API_KEY' \\"
	echo "     -H 'Content-Type: application/json' \\"
	echo "     -d '{\"query\": \"電腦\", \"limit\": 5}'"
else
	echo "📋 乾運行完成"
	echo "顯示了將執行的所有操作"
	echo ""
	echo "⚠️  注意事項:"
	echo "   1. 實際執行需要 sudo 權限"
	echo "   2. 確保已構建 release 版本: cargo build --release --bin momentry"
	echo "   3. 備份將創建在: $BACKUP_DIR"
	echo "   4. 服務將短暫中斷（約 10-15 秒）"
	echo ""
	echo "🚀 要實際執行部署，使用:"
	echo "   ./scripts/deployment/safe/deploy_dry_run.sh --execute"
	echo "   或"
	echo "   ./scripts/deployment/safe/deploy_dry_run.sh -e"
fi
