# Unity 脚本编译检查
$ErrorActionPreference = "Stop"
$projectRoot = Split-Path -Parent $PSScriptRoot
$unityEditor = "C:\Program Files\Unity\Hub\Editor\2022.3.62f3c1\Editor\Unity.exe"
$unityProject = "$projectRoot\src\Unity"

# 1. 重建 Core DLL
Write-Host "Building Core.dll..."
dotnet publish "$projectRoot\src\CounterDrone.Core\CounterDrone.Core.csproj" -c Release -o "$projectRoot\unity_plugins" 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) { Write-Host "Core.dll BUILD FAILED"; exit 1 }

# 2. 更新 Plugins + 清理缓存
Copy-Item "$projectRoot\unity_plugins\*.dll" "$unityProject\Assets\Plugins\CounterDrone.Core\" -Force
Remove-Item "$unityProject\Library\ScriptAssemblies" -Recurse -Force -ErrorAction SilentlyContinue
Write-Host "Compiling Unity scripts..."

# 3. 编译（-quit 确保编译完自动退出；超时 300s 兜底）
Write-Host "Compiling Unity scripts (timeout 300s)..."
$logFile = "$projectRoot\unity_build.log"
$proc = Start-Process -FilePath $unityEditor `
    -ArgumentList "-batchmode","-quit","-projectPath","`"$unityProject`"","-logFile","`"$logFile`"" `
    -PassThru -NoNewWindow
$proc | Wait-Process -Timeout 300 -ErrorAction SilentlyContinue

if (-not $proc.HasExited) {
    Write-Host "Unity build TIMEOUT (300s), killing process..."
    $proc | Stop-Process -Force
    exit 1
}
if ($proc.ExitCode -ne 0) {
    Write-Host "UNITY BUILD FAILED (exit code $($proc.ExitCode))"
    if (Test-Path $logFile) {
        Write-Host "--- Last 30 lines of log ---"
        Get-Content $logFile -Tail 30
    }
    exit 1
}

Write-Host "ALL CHECKS PASSED"
exit 0
