#!/bin/bash
# AI Agent 標準化命令接口
# 提供安全的、可預測的命令執行

set -e

VERSION="1.0.0"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

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

# 日誌函數
log_info() {
	echo -e "${BLUE}ℹ️  INFO:${NC} $1"
}

log_success() {
	echo -e "${GREEN}✅ SUCCESS:${NC} $1"
}

log_warning() {
	echo -e "${YELLOW}⚠️  WARNING:${NC} $1"
}

log_error() {
	echo -e "${RED}❌ ERROR:${NC} $1"
}

# 顯示幫助
show_help() {
	echo "Momentry Core AI Agent 命令接口 v$VERSION"
	echo ""
	echo "用法: ./agent_commands.sh <命令> [參數]"
	echo ""
	echo "可用命令:"
	echo "  check-status       檢查系統狀態 (只讀)"
	echo "  dry-run-deploy     部署乾運行模擬"
	echo "  test-development   啟動開發測試 (port 3003)"
	echo "  verify-production  驗證生產環境 (port 3002)"
	echo "  health-check       執行健康檢查"
	echo "  list-ports         列出端口使用情況"
	echo "  version            顯示版本信息"
	echo "  help               顯示此幫助"
	echo ""
	echo "示例:"
	echo "  ./agent_commands.sh check-status"
	echo "  ./agent_commands.sh dry-run-deploy"
	echo "  ./agent_commands.sh test-development"
	echo ""
	echo "安全特性:"
	echo "  • 所有操作都經過安全檢查"
	echo "  • 生產操作需要明確確認"
	echo "  • 提供乾運行模式"
}

# 命令：檢查狀態
command_check_status() {
	log_info "執行系統狀態檢查..."
	"$SCRIPT_DIR/validate_environment.sh"
	log_success "狀態檢查完成"
}

# 命令：部署乾運行
command_dry_run_deploy() {
	log_info "執行部署乾運行模擬..."
	"$SCRIPT_DIR/deploy_dry_run.sh"
	log_success "乾運行模擬完成"
}

# 命令：測試開發
command_test_development() {
	log_info "準備開發環境測試 (port 3003)..."

	# 檢查 port 3003 是否可用
	if lsof -ti:3003 >/dev/null 2>&1; then
		log_warning "port 3003 已被佔用"
		echo "佔用進程:"
		ps -p $(lsof -ti:3003) -o pid,command 2>/dev/null || true
		read -p "是否停止這些進程？(y/N): " CONFIRM
		if [ "$CONFIRM" = "y" ] || [ "$CONFIRM" = "Y" ]; then
			kill $(lsof -ti:3003) 2>/dev/null || true
			sleep 2
			log_success "已停止 port 3003 進程"
		else
			log_error "取消操作"
			exit 1
		fi
	fi

	# 檢查開發二進制文件
	if [ ! -f "/Users/accusys/momentry_core_0.1/target/release/momentry_playground" ]; then
		log_warning "開發二進制文件不存在"
		echo "請先構建: cargo build --release --bin momentry_playground"
		read -p "是否立即構建？(y/N): " BUILD_CONFIRM
		if [ "$BUILD_CONFIRM" = "y" ] || [ "$BUILD_CONFIRM" = "Y" ]; then
			log_info "構建開發二進制文件..."
			cd /Users/accusys/momentry_core_0.1
			cargo build --release --bin momentry_playground
			log_success "構建完成"
		else
			log_error "需要開發二進制文件才能繼續"
			exit 1
		fi
	fi

	# 檢查開發配置文件
	if [ ! -f "/Users/accusys/momentry_core_0.1/.env.development" ]; then
		log_warning "開發配置文件不存在 (.env.development)"
		echo "將使用默認配置"
	fi

	log_info "啟動開發服務器..."
	echo "執行命令:"
	echo "  cd /Users/accusys/momentry_core_0.1"
	echo "  source .env.development"
	echo "  cargo run --bin momentry_playground -- server"
	echo ""

	read -p "是否立即啟動？(y/N): " START_CONFIRM
	if [ "$CONFIRM" = "y" ] || [ "$CONFIRM" = "Y" ]; then
		cd /Users/accusys/momentry_core_0.1
		source .env.development 2>/dev/null || true
		cargo run --bin momentry_playground -- server
	else
		log_info "取消啟動，顯示命令供手動執行"
	fi

	log_success "開發測試準備完成"
}

# 命令：驗證生產
command_verify_production() {
	log_info "驗證生產環境 (port 3002)..."

	# 檢查是否有生產服務運行
	if ! lsof -ti:3002 >/dev/null 2>&1; then
		log_error "未找到運行在 port 3002 的生產服務"
		exit 1
	fi

	log_info "執行健康檢查..."
	MAX_RETRIES=3
	for i in $(seq 1 $MAX_RETRIES); do
		echo "嘗試 $i/$MAX_RETRIES..."
		if curl -f -s -o /dev/null --max-time 5 "http://localhost:3002/api/v1/health"; then
			log_success "生產服務健康 (HTTP 200 OK)"

			# 獲取更多信息
			echo ""
			echo "生產服務信息:"
			echo "  PID: $(lsof -ti:3002)"
			echo "  命令: $(ps -p $(lsof -ti:3002) -o command= 2>/dev/null || echo '未知')"
			echo "  啟動時間: $(ps -p $(lsof -ti:3002) -o lstart= 2>/dev/null || echo '未知')"

			# 測試搜索端點（只讀）
			log_info "測試搜索端點 (只讀)..."
			API_KEY_TEST="muser_f44690a514954a2b914e853a57e579de_1774728111_31de409b"
			if curl -s -o /dev/null -w "HTTP狀態碼: %{http_code}\n" --max-time 10 \
				-H "X-API-Key: $API_KEY_TEST" \
				-H "Content-Type: application/json" \
				-d '{"query": "test", "limit": 1}' \
				"http://localhost:3002/api/v1/n8n/search"; then
				log_success "搜索端點正常"
			else
				log_warning "搜索端點可能異常"
			fi

			exit 0
		fi

		if [ $i -lt $MAX_RETRIES ]; then
			echo "等待 2 秒後重試..."
			sleep 2
		fi
	done

	log_error "生產服務健康檢查失敗"
	exit 1
}

# 命令：健康檢查
command_health_check() {
	log_info "執行全面健康檢查..."

	echo "1. 端口檢查:"
	echo "   Port 3002 (生產): $(lsof -ti:3002 >/dev/null 2>&1 && echo '✅ 使用中' || echo '❌ 未使用')"
	echo "   Port 3003 (開發): $(lsof -ti:3003 >/dev/null 2>&1 && echo '✅ 使用中' || echo '✅ 可用')"

	echo ""
	echo "2. 服務檢查:"
	if lsof -ti:3002 >/dev/null 2>&1; then
		echo "   生產服務: ✅ 運行中 (PID: $(lsof -ti:3002))"
		# 健康檢查
		if curl -f -s -o /dev/null --max-time 3 "http://localhost:3002/api/v1/health"; then
			echo "   健康狀態: ✅ 正常"
		else
			echo "   健康狀態: ❌ 異常"
		fi
	else
		echo "   生產服務: ❌ 未運行"
	fi

	echo ""
	echo "3. 二進制文件檢查:"
	echo "   生產二進制: $([ -f "/Users/accusys/momentry_core_0.1/target/release/momentry" ] && echo '✅ 存在' || echo '❌ 缺失')"
	echo "   開發二進制: $([ -f "/Users/accusys/momentry_core_0.1/target/release/momentry_playground" ] && echo '✅ 存在' || echo '⚠️  缺失')"

	echo ""
	echo "4. 配置文件檢查:"
	echo "   生產配置: $([ -f "/Users/accusys/momentry_core_0.1/.env" ] && echo '✅ 存在' || echo '❌ 缺失')"
	echo "   開發配置: $([ -f "/Users/accusys/momentry_core_0.1/.env.development" ] && echo '✅ 存在' || echo '❌ 缺失')"

	log_success "健康檢查完成"
}

# 命令：列出端口
command_list_ports() {
	log_info "列出端口使用情況..."

	echo "Momentry Core 相關端口:"
	echo "----------------------------------------"

	# 檢查標準端口
	PORTS="3002 3003 5432 6379 27017 6333 3306 8080 8081"

	for PORT in $PORTS; do
		SERVICE_NAME=""
		case $PORT in
		3002) SERVICE_NAME="生產API" ;;
		3003) SERVICE_NAME="開發API" ;;
		5432) SERVICE_NAME="PostgreSQL" ;;
		6379) SERVICE_NAME="Redis" ;;
		27017) SERVICE_NAME="MongoDB" ;;
		6333) SERVICE_NAME="Qdrant" ;;
		3306) SERVICE_NAME="MariaDB" ;;
		8080) SERVICE_NAME="n8n" ;;
		8081) SERVICE_NAME="Gitea" ;;
		esac

		if lsof -ti:$PORT >/dev/null 2>&1; then
			PID=$(lsof -ti:$PORT | head -1)
			PROCESS=$(ps -p $PID -o command= 2>/dev/null | cut -c1-50 || echo "未知")
			echo "✅ $PORT ($SERVICE_NAME): 使用中"
			echo "   PID: $PID"
			echo "   進程: $PROCESS..."
		else
			echo "❌ $PORT ($SERVICE_NAME): 未使用"
		fi
		echo ""
	done

	log_success "端口列表完成"
}

# 主命令處理
COMMAND="${1:-help}"

case "$COMMAND" in
"check-status" | "status")
	command_check_status
	;;
"dry-run-deploy" | "dryrun")
	command_dry_run_deploy
	;;
"test-development" | "test-dev")
	command_test_development
	;;
"verify-production" | "verify")
	command_verify_production
	;;
"health-check" | "health")
	command_health_check
	;;
"list-ports" | "ports")
	command_list_ports
	;;
"version" | "v")
	echo "Momentry Core AI Agent 命令接口 v$VERSION"
	;;
"help" | "--help" | "-h")
	show_help
	;;
*)
	log_error "未知命令: $COMMAND"
	echo ""
	show_help
	exit 1
	;;
esac
