#!/bin/bash
#==============================================================================
# Momentry System - Initial Setup Script
# 適用於全新 Mac 的系統準備腳本
#==============================================================================

set -e

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

# 變數
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
MOMENTRY_DIR="/Users/accusys/momentry"
CURRENT_USER=$(whoami)

#==============================================================================
# 函數定義
#==============================================================================

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"
}

check_root() {
	if [ "$EUID" -eq 0 ]; then
		log_warning "不建議使用 root 執行此腳本"
	fi
}

#==============================================================================
# 主要流程
#==============================================================================

main() {
	echo "=========================================="
	echo "Momentry System - Initial Setup"
	echo "=========================================="
	echo ""

	check_root

	# Step 1: 建立目錄結構
	log_info "Step 1/5: 建立目錄結構..."

	mkdir -p "$MOMENTRY_DIR"/{var,etc,log,scripts,backup}
	mkdir -p "$MOMENTRY_DIR/var"/{postgresql,mongodb,mariadb,redis,qdrant,n8n,ollama,sftpgo}
	mkdir -p "$MOMENTRY_DIR/etc"/{sftpgo,caddy,gitea,php}
	mkdir -p "$MOMENTRY_DIR/backup"/{daily,weekly,monthly}
	mkdir -p /Users/accusys/workspace/sftpgo
	mkdir -p /Users/accusys/sftpgo_test/{demo,uploads}

	chown -R "$CURRENT_USER":staff "$MOMENTRY_DIR" 2>/dev/null || true
	chown -R "$CURRENT_USER":staff /Users/accusys/workspace 2>/dev/null || true
	chown -R "$CURRENT_USER":staff /Users/accusys/sftpgo_test 2>/dev/null || true

	log_success "目錄結構建立完成"

	# Step 2: 檢查 Homebrew
	log_info "Step 2/5: 檢查 Homebrew..."

	if ! command -v brew &>/dev/null; then
		log_warning "Homebrew 未安裝"
		echo ""
		echo "請執行以下命令安裝 Homebrew:"
		echo "/bin/bash -c \"\$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\""
		echo ""
		echo "安裝完成後，重新執行此腳本"
		exit 1
	fi

	log_success "Homebrew 已安裝: $(brew --version | head -1)"

	# Step 3: 檢查必要工具
	log_info "Step 3/5: 檢查必要工具..."

	TOOLS=("git" "curl" "jq" "tree")
	MISSING_TOOLS=()

	for tool in "${TOOLS[@]}"; do
		if ! command -v "$tool" &>/dev/null; then
			MISSING_TOOLS+=("$tool")
		fi
	done

	if [ ${#MISSING_TOOLS[@]} -gt 0 ]; then
		log_warning "缺少以下工具: ${MISSING_TOOLS[*]}"
		echo ""
		read -p "是否自動安裝這些工具? (y/n): " -n 1 -r
		echo ""
		if [[ $REPLY =~ ^[Yy]$ ]]; then
			brew install "${MISSING_TOOLS[@]}"
			log_success "工具安裝完成"
		else
			log_warning "跳過工具安裝"
		fi
	else
		log_success "所有必要工具已安裝"
	fi

	# Step 4: 檢查服務狀態
	log_info "Step 4/5: 檢查服務狀態..."

	echo ""
	echo "  PostgreSQL: $(pg_isready -h 127.0.0.1 -p 5432 >/dev/null 2>&1 && echo '✅ 運行中' || echo '❌ 未運行')"
	echo "  Redis: $(redis-cli -a accusys ping >/dev/null 2>&1 && echo '✅ 運行中' || echo '❌ 未運行')"
	echo "  MongoDB: $(mongosh --quiet --eval "db.adminCommand('ping')" >/dev/null 2>&1 && echo '✅ 運行中' || echo '❌ 未運行')"
	echo "  Ollama: $(curl -s http://localhost:11434/api/tags >/dev/null 2>&1 && echo '✅ 運行中' || echo '❌ 未運行')"
	echo "  n8n: $(curl -s http://localhost:5678 >/dev/null 2>&1 && echo '✅ 運行中' || echo '❌ 未運行')"
	echo "  SFTPGo: $(curl -s http://localhost:8080 >/dev/null 2>&1 && echo '✅ 運行中' || echo '❌ 未運行')"
	echo "  Qdrant: $(curl -s http://localhost:6333/ >/dev/null 2>&1 && echo '✅ 運行中' || echo '❌ 未運行')"
	echo "  Momentry API: $(curl -s http://localhost:3002/health >/dev/null 2>&1 && echo '✅ 運行中' || echo '❌ 未運行')"
	echo ""

	# Step 5: 建立快捷指令
	log_info "Step 5/5: 建立快捷指令..."

	cat >/Users/accusys/momentry/scripts/health_check.sh <<'HEALTH_EOF'
#!/bin/bash
echo "=========================================="
echo "Momentry System Health Check"
echo "=========================================="
echo ""

pg_isready -h 127.0.0.1 -p 5432 > /dev/null 2>&1 && echo "✅ PostgreSQL" || echo "❌ PostgreSQL"
redis-cli -a accusys ping > /dev/null 2>&1 && echo "✅ Redis" || echo "❌ Redis"
mongosh --quiet --eval "db.adminCommand('ping')" > /dev/null 2>&1 && echo "✅ MongoDB" || echo "❌ MongoDB"
curl -s http://localhost:11434/api/tags > /dev/null 2>&1 && echo "✅ Ollama" || echo "❌ Ollama"
curl -s http://localhost:5678 > /dev/null 2>&1 && echo "✅ n8n" || echo "❌ n8n"
curl -s http://localhost:8080 > /dev/null 2>&1 && echo "✅ SFTPGo" || echo "❌ SFTPGo"
curl -s http://localhost:6333/ > /dev/null 2>&1 && echo "✅ Qdrant" || echo "❌ Qdrant"
curl -s http://localhost:3002/health > /dev/null 2>&1 && echo "✅ Momentry API" || echo "❌ Momentry API"

echo ""
HEALTH_EOF

	chmod +x /Users/accusys/momentry/scripts/health_check.sh
	log_success "快捷指令已建立: /Users/accusys/momentry/scripts/health_check.sh"

	# 完成
	echo ""
	echo "=========================================="
	log_success "初始設定完成!"
	echo "=========================================="
	echo ""
	echo "下一步:"
	echo "  1. 查看完整安裝指南: docs/FRESH_MAC_INSTALLATION.md"
	echo "  2. 執行健康檢查: /Users/accusys/momentry/scripts/health_check.sh"
	echo "  3. 查閱服務密碼: docs/FRESH_MAC_INSTALLATION.md#第八部分"
	echo ""
}

# 執行
main "$@"
