# 设置控制台输出编码为 UTF-8，防止乱码
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

$Green = "Green"
$Red = "Red"
$Yellow = "Yellow"
$Blue = "Cyan"

Write-Host "[信息] 正在检查 Docker 环境..." -ForegroundColor $Blue

# 切换到脚本所在目录，确保 docker-compose 命令能找到配置文件
Push-Location $PSScriptRoot

# 检查是否安装了 Docker
if (-not (Get-Command docker -ErrorAction SilentlyContinue)) {
    Write-Host "[错误] 未找到 Docker，请先安装 Docker Desktop。" -ForegroundColor $Red
    Read-Host "按回车键退出"
    exit
}

try {
{% if action == 'start' %}
    Write-Host "[信息] 正在启动服务 (构建并后台运行)..." -ForegroundColor $Blue
    # 使用 -d 后台运行，--build 确保镜像更新
    docker-compose up -d --build

    if ($LASTEXITCODE -eq 0) {
        Write-Host ""
        Write-Host "[成功] 服务启动成功！" -ForegroundColor $Green
        Write-Host "----------------------------------------------------"
        Write-Host "Web 应用地址:   http://localhost:8000" -ForegroundColor $Yellow
        Write-Host "API 文档地址:   http://localhost:8000/docs" -ForegroundColor $Yellow
        Write-Host "Redis 端口:     6379" -ForegroundColor $Yellow
        Write-Host "----------------------------------------------------"
        Write-Host "[提示] 使用 'docker-compose logs -f' 查看实时日志。" -ForegroundColor $Blue
        Write-Host "[提示] 使用 '.\stop_docker.ps1' 停止服务。" -ForegroundColor $Blue
    } else {
        Write-Host "[错误] 服务启动失败，请检查 Docker 日志。" -ForegroundColor $Red
    }

{% elif action == 'stop' %}
    Write-Host "[信息] 正在停止服务..." -ForegroundColor $Blue
    docker-compose down

    if ($LASTEXITCODE -eq 0) {
        Write-Host "[成功] 服务已完全停止。" -ForegroundColor $Green
    } else {
        Write-Host "[错误] 停止服务时遇到问题。" -ForegroundColor $Red
    }

{% elif action == 'restart' %}
    Write-Host "[信息] 正在重启服务..." -ForegroundColor $Blue
    Write-Host "[1/2] 停止服务..."
    docker-compose down
    
    Write-Host "[2/2] 重新启动服务..."
    docker-compose up -d --build

    if ($LASTEXITCODE -eq 0) {
        Write-Host ""
        Write-Host "[成功] 服务重启完成！" -ForegroundColor $Green
        Write-Host "----------------------------------------------------"
        Write-Host "Web 应用地址:   http://localhost:8000" -ForegroundColor $Yellow
        Write-Host "API 文档地址:   http://localhost:8000/docs" -ForegroundColor $Yellow
        Write-Host "----------------------------------------------------"
    } else {
        Write-Host "[错误] 重启服务失败。" -ForegroundColor $Red
    }
{% endif %}
}
finally {
    # 恢复原来的目录
    Pop-Location
}

Write-Host ""
Read-Host "按回车键关闭"
