#!/bin/bash
# test_docker_local.sh - 本機測試 Docker 部署
set -e

echo "=========================================="
echo "本機 Docker 測試"
echo "=========================================="

# 檢查 Docker 是否安裝
if ! command -v docker &> /dev/null; then
    echo "❌ Docker 未安裝"
    echo "   請安裝 Docker Desktop: https://www.docker.com/products/docker-desktop"
    exit 1
fi

# 檢查 Docker 是否運行
if ! docker info &> /dev/null; then
    echo "❌ Docker 未運行"
    echo "   請啟動 Docker Desktop"
    exit 1
fi

# 檢查 .env 檔案
if [ ! -f ".env" ]; then
    echo "⚠️  找不到 .env 檔案"
    read -p "是否建立 .env 檔案？(y/n): " CREATE_ENV
    if [ "$CREATE_ENV" = "y" ]; then
        cat > .env <<EOF
# Flask 設定
FLASK_ENV=production
SECRET_KEY=$(openssl rand -hex 32)

# Email 設定
EMAIL_USER=your-email@gmail.com
EMAIL_PASSWORD=your-app-password
SMTP_SERVER=smtp.gmail.com
SMTP_PORT=587

# 資料庫
DATABASE_PATH=data/momo_database.db
EOF
        echo "✅ 已建立 .env 檔案，請編輯後再次執行此腳本"
        exit 0
    fi
fi

# 停止現有容器
echo ""
echo "🛑 停止現有容器..."
docker-compose down 2>/dev/null || true

# 建立並啟動容器
echo ""
echo "🔨 建立 Docker 映像..."
docker-compose build

echo ""
echo "🚀 啟動容器..."
docker-compose up -d

# 等待服務啟動
echo ""
echo "⏳ 等待服務啟動..."
sleep 5

# 檢查容器狀態
echo ""
echo "📊 容器狀態："
docker-compose ps

# 測試健康檢查
echo ""
echo "🏥 測試健康檢查..."
if curl -f http://localhost:80/health &>/dev/null; then
    echo "✅ 健康檢查通過"
else
    echo "⚠️  健康檢查失敗，查看日誌："
    docker-compose logs --tail=20
fi

echo ""
echo "=========================================="
echo "✅ Docker 容器已啟動！"
echo "=========================================="
echo ""
echo "🌐 訪問應用: http://localhost"
echo ""
echo "📋 查看日誌:"
echo "   docker-compose logs -f"
echo ""
echo "🔍 進入容器:"
echo "   docker exec -it momo-pro-system bash"
echo ""
echo "🛑 停止容器:"
echo "   docker-compose down"
echo ""
echo "🗑️  刪除所有數據:"
echo "   docker-compose down -v"
echo ""
