# 元泰 EG Windows 构建脚本 - Nuitka
param([string]$Version = "1.0.0")

$ErrorActionPreference = "Stop"
$ProjectRoot = "C:\Users\Tellme\apps\EG"
$BuildDir = "$ProjectRoot\build"
$DistDir = "$ProjectRoot\dist\EG_$Version"
$DataDirs = @(
    "config",
    "icons",
    "Resources",
    "tex",
    "templates",
    "core",
    "gui",
    "project",
    "scene",
    "scripts",
    "ssbo_component",
    "tools",
    "TransformGizmo",
    "ui",
    "RenderPipelineFile",
    "vr_actions",
    "new",
    "demo"
)
$DataFiles = @(
    "imgui.ini"
)
$RequiredPackages = @(
    "panda3d",
    "direct",
    "imgui_bundle",
    "p3dimgui",
    "openvr",
    "RenderPipelineFile",
    "rpcore",
    "rplibs",
    "rpplugins",
    "core",
    "scene",
    "project",
    "ui",
    "gui",
    "scripts",
    "ssbo_component",
    "tools",
    "TransformGizmo",
    "vr_actions"
)
$OptionalPackages = @(
    "plugins",
    "gltf",
    "playwright",
    "PyQt5"
)
$OptionalModules = @(
    "playwright.async_api",
    "win32gui",
    "win32con",
    "PyQt5.QtCore",
    "PyQt5.QtGui",
    "PyQt5.QtWidgets"
)

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  元泰 EG 构建 (Nuitka)" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan

# 必须在 VS Dev Shell 中运行
if (!(Get-Command cl -ErrorAction SilentlyContinue)) {
    Write-Host "错误: 请在 VS Dev Shell 中运行此脚本" -ForegroundColor Red
    exit 1
}

# 清理
Write-Host "`n[1/4] 清理..." -ForegroundColor Yellow
Remove-Item $BuildDir -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item $DistDir -Recurse -Force -ErrorAction SilentlyContinue
New-Item -ItemType Directory -Force -Path $DistDir | Out-Null
Write-Host "    完成" -ForegroundColor Green

# 设置环境
Write-Host "`n[2/4] 设置环境..." -ForegroundColor Yellow
$env:PYTHONPATH = "$ProjectRoot;$ProjectRoot\RenderPipelineFile"
$env:PYTHONDONTWRITEBYTECODE = "1"

$imguiPath = (py -3.11 -c "import imgui_bundle, os; print(os.path.dirname(imgui_bundle.__file__))").Replace('\', '/')
$glfwDll = "$imguiPath/glfw3.dll"
Write-Host "    glfw3.dll: $glfwDll" -ForegroundColor Gray

function Test-PythonImportable {
    param([string]$ModuleName)

    & py -3.11 -c "import importlib.util, sys; sys.exit(0 if importlib.util.find_spec('$ModuleName') else 1)" | Out-Null
    return ($LASTEXITCODE -eq 0)
}

$requiredPackageArgs = @()
foreach ($package in $RequiredPackages) {
    $requiredPackageArgs += "--include-package=$package"
}

$detectedOptionalPackageArgs = @()
foreach ($package in $OptionalPackages) {
    if (Test-PythonImportable $package) {
        $detectedOptionalPackageArgs += "--include-package=$package"
        Write-Host "    检测到可选包并纳入打包: $package" -ForegroundColor Gray
    }
}

$detectedOptionalModuleArgs = @()
foreach ($module in $OptionalModules) {
    if (Test-PythonImportable $module) {
        $detectedOptionalModuleArgs += "--include-module=$module"
        Write-Host "    检测到可选模块并纳入打包: $module" -ForegroundColor Gray
    }
}

# Nuitka 编译
Write-Host "`n[3/4] Nuitka 编译 (预计 20-40 分钟)..." -ForegroundColor Yellow
Write-Host "    关键修复: 使用正斜杠作为目标路径" -ForegroundColor Gray
Write-Host ""

$nuitkaArgs = @(
    "-m", "nuitka"
    "--standalone"
    "--follow-import-to=rpcore"
    "--follow-import-to=rpplugins"
    "--follow-import-to=core"
    "--follow-import-to=scene"
    "--follow-import-to=project"
    "--follow-import-to=ui"
    "--nofollow-import-to=tkinter,test,unittest,setuptools,pip"
    # 关键: 正斜杠作为目标路径
    "--include-data-files=$glfwDll=imgui_bundle/glfw3.dll"
    "--windows-icon-from-ico=icons/app.ico"
    "--windows-console-mode=disable"
    "--windows-company-name=元泰"
    "--windows-product-name=元泰 EG"
    "--windows-file-version=$Version"
    "--windows-product-version=$Version"
    "--output-dir=$BuildDir"
    "--jobs=8"
    "--lto=no"
    "Start_Run.py"
)

$nuitkaArgs += $requiredPackageArgs
$nuitkaArgs += $detectedOptionalPackageArgs
$nuitkaArgs += $detectedOptionalModuleArgs

& py -3.11 @nuitkaArgs

if ($LASTEXITCODE -ne 0) {
    Write-Host "`n[错误] 编译失败!" -ForegroundColor Red
    exit 1
}

Write-Host "`n    编译成功" -ForegroundColor Green

# 复制到输出目录
Write-Host "`n[4/4] 整理输出..." -ForegroundColor Yellow
$sourceDir = "$BuildDir\Start_Run.dist"
Copy-Item "$sourceDir\*" $DistDir -Recurse -Force

# 复制项目运行时资源。Nuitka 会收集 Python 模块，但这些目录里的配置、
# shader、模型、图标等仍然需要以真实文件形式存在于 dist 中。
foreach ($dir in $DataDirs) {
    $sourcePath = Join-Path $ProjectRoot $dir
    if (Test-Path $sourcePath) {
        Copy-Item $sourcePath (Join-Path $DistDir $dir) -Recurse -Force
        Write-Host "    已复制目录: $dir" -ForegroundColor Gray
    }
}

foreach ($file in $DataFiles) {
    $sourcePath = Join-Path $ProjectRoot $file
    if (Test-Path $sourcePath) {
        Copy-Item $sourcePath $DistDir -Force
        Write-Host "    已复制文件: $file" -ForegroundColor Gray
    }
}

# 重命名 exe
if (Test-Path "$DistDir\Start_Run.exe") {
    Rename-Item "$DistDir\Start_Run.exe" "元泰.exe"
}

$exeSize = [math]::Round((Get-Item "$DistDir\元泰.exe").Length / 1MB, 2)
Write-Host "    元泰.exe ($exeSize MB)" -ForegroundColor Green

# 完成
Write-Host "`n========================================" -ForegroundColor Green
Write-Host "  构建完成!" -ForegroundColor Green
Write-Host "========================================" -ForegroundColor Green
Write-Host "输出: $DistDir\元泰.exe" -ForegroundColor White
Write-Host ""
Write-Host "测试运行:" -ForegroundColor Yellow
Write-Host "  $DistDir\元泰.exe" -ForegroundColor Gray
