# =============================================================================
# 企微智能IT支持服务台 — 打包部署脚本
# =============================================================================
# 功能：将所有部署所需文件打包成一个 zip 文件
# 用法：在 PowerShell 中运行此脚本
# 输出：it-smart-desk-server-deploy.zip
# =============================================================================

$ErrorActionPreference = "Stop"

# 获取项目根目录（脚本所在目录的父目录的父目录）
$projectRoot = $PSScriptRoot
# 如果在 deploy-server 子目录运行，向上一级
if ($projectRoot -match "deploy-server") {
    $projectRoot = Split-Path -Parent $projectRoot
}
$deployDir = "$projectRoot\deploy-server"
$packageDir = "$deployDir\_package"
$zipFile = "$deployDir\it-smart-desk-server-deploy.zip"

Write-Host "========================================" -ForegroundColor Cyan
Write-Host " 企微智能IT支持服务台 — 打包部署文件" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# 清理旧的打包目录
if (Test-Path $packageDir) {
    Remove-Item $packageDir -Recurse -Force
    Write-Host "[1/7] 清理旧打包目录... done" -ForegroundColor Gray
} else {
    Write-Host "[1/7] 创建打包目录..." -ForegroundColor Gray
}
New-Item -ItemType Directory -Path $packageDir -Force | Out-Null

# 复制 docker-compose.yml
Write-Host "[2/7] 复制 docker-compose.yml..." -ForegroundColor Yellow
Copy-Item "$deployDir\docker-compose.yml" "$packageDir\docker-compose.yml"

# 复制 .env（含真实配置）
Write-Host "[3/7] 复制 .env（含真实配置）..." -ForegroundColor Yellow
Copy-Item "$deployDir\.env" "$packageDir\.env"

# 复制 nginx 配置
Write-Host "[4/7] 复制 nginx 配置..." -ForegroundColor Yellow
New-Item -ItemType Directory -Path "$packageDir\nginx" -Force | Out-Null
Copy-Item "$deployDir\nginx.conf" "$packageDir\nginx\nginx.conf"

# 复制后端代码
Write-Host "[5/7] 复制后端代码（含 Dockerfile）..." -ForegroundColor Yellow
$backendSrc = "$projectRoot\backend"
$backendDst = "$packageDir\backend"
New-Item -ItemType Directory -Path $backendDst -Force | Out-Null

# 复制后端核心文件（排除 __pycache__、.pyc、.db 等）
$backendFiles = @(
    "Dockerfile",
    "requirements.txt",
    "alembic.ini",
    "alembic",
    "app"
)
foreach ($item in $backendFiles) {
    $src = "$backendSrc\$item"
    if (Test-Path $src) {
        if ((Get-Item $src).PSIsContainer) {
            # 复制目录，排除 __pycache__ 和 .pyc
            robocopy $src "$backendDst\$item" /E /XD __pycache__ /XF *.pyc *.db /NFL /NDL /NJH /NJS /NC /NS /NP | Out-Null
        } else {
            Copy-Item $src "$backendDst\$item"
        }
    }
}

# 复制前端构建产物
Write-Host "[6/7] 复制前端构建产物..." -ForegroundColor Yellow
@("frontend-h5", "frontend-agent", "frontend-admin") | ForEach-Object {
    $src = "$projectRoot\$_\dist"
    $dst = "$packageDir\$_\dist"
    if (Test-Path $src) {
        robocopy $src $dst /E /NFL /NDL /NJH /NJS /NC /NS /NP | Out-Null
        $count = (Get-ChildItem $dst -Recurse -File).Count
        Write-Host "  $_ : $count files" -ForegroundColor Gray
    } else {
        Write-Host "  $_ : WARNING - dist not found!" -ForegroundColor Red
    }
}

# 打包成 zip
Write-Host "[7/7] 打包成 zip..." -ForegroundColor Yellow
if (Test-Path $zipFile) {
    Remove-Item $zipFile -Force
}
Compress-Archive -Path "$packageDir\*" -DestinationPath $zipFile -CompressionLevel Optimal

# 清理临时目录
Remove-Item $packageDir -Recurse -Force

# 输出结果
$zipSize = [math]::Round((Get-Item $zipFile).Length / 1MB, 2)
Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host " 打包完成！" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host "  文件：$zipFile" -ForegroundColor White
Write-Host "  大小：${zipSize} MB" -ForegroundColor White
Write-Host ""
Write-Host "下一步：" -ForegroundColor Cyan
Write-Host "  1. 上传 zip 到服务器 /opt/wecom-it-desk/" -ForegroundColor White
Write-Host "  2. 解压：unzip it-smart-desk-server-deploy.zip" -ForegroundColor White
Write-Host "  3. 启动：docker compose up -d --build" -ForegroundColor White
Write-Host "  4. 参考 DEPLOY-GUIDE.md 查看详细步骤" -ForegroundColor White
