<#
.SYNOPSIS
    服务器环境初始化脚本：删除 skip-worktree 排除的文件/目录 + 创建 export 目录树。

.DESCRIPTION
    在服务器上 git clone + setup-server-git.py 之后运行。
    1. 删除已被 skip-worktree 标记的目录和散文件（释放磁盘空间）
    2. 创建完整的 export/ 目录树（ETL/SYSTEM/BACKEND 三大类）

    三个环境都需要 export 目录（LOG、JSON、REPORTS 等运行时输出在每个环境都会产生）。

.PARAMETER Envs
    要初始化的环境列表，默认 test,prod。
    可选值：test, prod（逗号分隔）。

.EXAMPLE
    # 初始化 test + prod（默认）
    .\init-server-env.ps1

    # 只初始化 test
    .\init-server-env.ps1 -Envs test

    # 只初始化 prod
    .\init-server-env.ps1 -Envs prod
#>

param(
    [string[]]$Envs = @("test", "prod")
)

$ErrorActionPreference = "Stop"

# ============================================================================
# 配置
# ============================================================================

# 服务器根目录
$ServerRoot = "D:\NeoZQYY"

# 环境 → repo 路径映射
$EnvPaths = @{
    "test" = "$ServerRoot\test\repo"
    "prod" = "$ServerRoot\prod\repo"
}

# skip-worktree 后可安全删除的目录（与 setup-server-git.py DELETABLE_DIRS 一致）
$DeletableDirs = @(
    "export"
    "docs"
    "tests"
    "samples"
    "infra"
    ".kiro"
    ".hypothesis"
    ".pytest_cache"
    "apps\miniprogram"
    "scripts\ops"
    "scripts\audit"
    "scripts\migrate"
)

# 可安全删除的根目录散文件（与 setup-server-git.py SKIP_PREFIXES 中的散文件一致）
$DeletableFiles = @(
    "coach-detail-full.png"
    "customer-detail-full.png"
    "perf-records-current.png"
    "white-screen-debug.png"
    "NeoZQYY.code-workspace"
    "start-admin.bat"
    ".kiroignore"
)

# export 目录树（所有环境通用，运行时输出在每个环境都会产生）
$ExportDirs = @(
    "export\ETL-Connectors\feiqiu\JSON"
    "export\ETL-Connectors\feiqiu\LOGS"
    "export\ETL-Connectors\feiqiu\REPORTS"
    "export\SYSTEM\LOGS"
    "export\SYSTEM\REPORTS\dataflow_analysis"
    "export\SYSTEM\REPORTS\field_audit"
    "export\SYSTEM\REPORTS\full_dataflow_doc"
    "export\SYSTEM\CACHE\api_samples"
    "export\BACKEND\LOGS"
)


# ============================================================================
# 函数
# ============================================================================

function Remove-SkipWorktreeItems {
    <#
    .SYNOPSIS
        删除指定 repo 下已被 skip-worktree 标记的目录和散文件。
    #>
    param([string]$RepoPath)

    Write-Host "`n  [删除] 清理 skip-worktree 排除的目录和文件..." -ForegroundColor Yellow

    $freedMB = 0

    # 删除目录
    foreach ($dir in $DeletableDirs) {
        $fullPath = Join-Path $RepoPath $dir
        if (Test-Path $fullPath) {
            $size = (Get-ChildItem $fullPath -Recurse -File -ErrorAction SilentlyContinue |
                     Measure-Object -Property Length -Sum).Sum
            $sizeMB = [math]::Round($size / 1MB, 1)
            Remove-Item $fullPath -Recurse -Force
            Write-Host "    已删除: $dir/ ($sizeMB MB)" -ForegroundColor Red
            $freedMB += $sizeMB
        } else {
            Write-Host "    跳过:   $dir/ (不存在)" -ForegroundColor DarkGray
        }
    }

    # 删除散文件
    foreach ($file in $DeletableFiles) {
        $fullPath = Join-Path $RepoPath $file
        if (Test-Path $fullPath) {
            $size = (Get-Item $fullPath).Length
            $sizeMB = [math]::Round($size / 1MB, 2)
            Remove-Item $fullPath -Force
            Write-Host "    已删除: $file ($sizeMB MB)" -ForegroundColor Red
            $freedMB += $sizeMB
        }
    }

    # 删除根目录下所有 .png 文件（server-exclude.txt 中 *.png 规则）
    Get-ChildItem $RepoPath -Filter "*.png" -File -ErrorAction SilentlyContinue | ForEach-Object {
        $sizeMB = [math]::Round($_.Length / 1MB, 2)
        Remove-Item $_.FullName -Force
        Write-Host "    已删除: $($_.Name) ($sizeMB MB)" -ForegroundColor Red
        $freedMB += $sizeMB
    }

    Write-Host "    共释放: $freedMB MB" -ForegroundColor Green
}

function New-ExportTree {
    <#
    .SYNOPSIS
        在指定 repo 下创建完整的 export 目录树。
    #>
    param([string]$RepoPath)

    Write-Host "`n  [创建] 初始化 export 目录树..." -ForegroundColor Yellow

    foreach ($dir in $ExportDirs) {
        $fullPath = Join-Path $RepoPath $dir
        if (-not (Test-Path $fullPath)) {
            New-Item -ItemType Directory -Path $fullPath -Force | Out-Null
            Write-Host "    已创建: $dir/" -ForegroundColor Cyan
        } else {
            Write-Host "    已存在: $dir/" -ForegroundColor DarkGray
        }
    }
}

function Test-GitSetup {
    <#
    .SYNOPSIS
        检查 setup-server-git.py 是否已运行（通过检查 .git/info/exclude 内容）。
    #>
    param([string]$RepoPath)

    $excludeFile = Join-Path $RepoPath ".git\info\exclude"
    if (-not (Test-Path $excludeFile)) {
        return $false
    }
    $content = Get-Content $excludeFile -Raw -ErrorAction SilentlyContinue
    return ($content -match "server-exclude")
}

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

Write-Host "============================================" -ForegroundColor White
Write-Host " NeoZQYY 服务器环境初始化" -ForegroundColor White
Write-Host " 目标环境: $($Envs -join ', ')" -ForegroundColor White
Write-Host "============================================" -ForegroundColor White

foreach ($env in $Envs) {
    $repoPath = $EnvPaths[$env]

    if (-not $repoPath) {
        Write-Host "`n[错误] 未知环境: $env（可选: test, prod）" -ForegroundColor Red
        continue
    }

    Write-Host "`n========== 环境: $env ==========" -ForegroundColor Magenta
    Write-Host "  路径: $repoPath"

    # 检查 repo 是否存在
    if (-not (Test-Path $repoPath)) {
        Write-Host "  [警告] 目录不存在，跳过。请先 git clone。" -ForegroundColor Yellow
        continue
    }

    # 检查 setup-server-git.py 是否已运行
    if (-not (Test-GitSetup $repoPath)) {
        Write-Host "  [警告] 未检测到 setup-server-git.py 的配置。" -ForegroundColor Yellow
        Write-Host "         建议先运行: python scripts/server/setup-server-git.py" -ForegroundColor Yellow
        $answer = Read-Host "  是否继续删除操作？(y/N)"
        if ($answer -ne "y" -and $answer -ne "Y") {
            Write-Host "  已跳过 $env 环境的删除操作。" -ForegroundColor DarkGray
            # 仍然创建 export 目录
            New-ExportTree -RepoPath $repoPath
            continue
        }
    }

    # 步骤 1：删除排除的文件/目录
    Remove-SkipWorktreeItems -RepoPath $repoPath

    # 步骤 2：创建 export 目录树
    New-ExportTree -RepoPath $repoPath

    Write-Host "`n  [完成] $env 环境初始化完毕。" -ForegroundColor Green
}

Write-Host "`n============================================" -ForegroundColor White
Write-Host " 全部完成。" -ForegroundColor Green
Write-Host ""
Write-Host " 后续步骤:" -ForegroundColor White
Write-Host "   1. 手动创建各环境的 .env 文件（参考 .env.template）" -ForegroundColor White
Write-Host "   2. 确认 .env 中的 export 路径指向 repo/export/ 下对应子目录" -ForegroundColor White
Write-Host "   3. 运行 uv sync --all-packages 安装依赖" -ForegroundColor White
Write-Host "============================================" -ForegroundColor White
