# 组装发布目录与 zip。
#
# 产物结构(安装器要求 folderdock-setup.exe 与 folderdock.exe 放在同一目录):
#   dist/FolderDock/folderdock.exe         主程序
#   dist/FolderDock/folderdock-setup.exe   安装器(也是卸载器)
#   dist/FolderDock/README.md              说明
#   dist/FolderDock/LICENSE
#   dist/FolderDock-<版本>.zip             整个目录打包
#
# 用法:
#   powershell -ExecutionPolicy Bypass -File scripts/dist.ps1          # 用 debug 构建(快,日常验证)
#   powershell -ExecutionPolicy Bypass -File scripts/dist.ps1 -Release # 用 release 构建

param(
    [switch]$Release,
    [string]$Out = "dist"
)

$ErrorActionPreference = "Stop"
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
Push-Location $root
try {
    $profile = if ($Release) { "release" } else { "debug" }
    $cargoArgs = @("build", "--bins")
    if ($Release) { $cargoArgs += "--release" }
    Write-Host "==> cargo $($cargoArgs -join ' ')"
    & cargo @cargoArgs
    if ($LASTEXITCODE -ne 0) { throw "cargo build 失败(退出码 $LASTEXITCODE)" }

    $exe = if ($Release) { "folderdock.exe" } else { "folderdock.exe" }
    $setup = if ($Release) { "folderdock-setup.exe" } else { "folderdock-setup.exe" }
    $srcDir = Join-Path $root "target/$profile"

    $dest = Join-Path $root "$Out/FolderDock"
    if (Test-Path $dest) { Remove-Item -Recurse -Force $dest }
    New-Item -ItemType Directory -Force -Path $dest | Out-Null

    foreach ($f in @($exe, $setup)) {
        $from = Join-Path $srcDir $f
        if (-not (Test-Path $from)) { throw "缺少构建产物:$from" }
        Copy-Item $from (Join-Path $dest $f)
    }
    foreach ($f in @("README.md", "LICENSE")) {
        $from = Join-Path $root $f
        if (Test-Path $from) { Copy-Item $from (Join-Path $dest $f) }
    }

    $version = (& cargo metadata --no-deps --format-version 1 | ConvertFrom-Json).packages[0].version

    # ---- 资源段守卫:图标与版本信息必须真的进了 exe ----
    # 以前 exe 没有资源段,构建照样成功、装完才发现满屏通用空白图标。这里在打包末尾
    # 直接把图标从 exe 里读出来;读不到就让打包失败,而不是把没图标的产物发出去。
    # 用 PrivateExtractIcons 而不是 System.Drawing.Icon.ExtractAssociatedIcon:后者对
    # 没有图标的 exe 也会返回系统通用图标,测不出缺失。
    if (-not ("FolderDockIconProbe" -as [type])) {
        Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public static class FolderDockIconProbe {
    [DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int PrivateExtractIcons(string file, int index, int cx, int cy, IntPtr[] icons, uint[] ids, int nIcons, uint flags);
    [DllImport("user32.dll")]
    public static extern bool DestroyIcon(IntPtr icon);
}
"@
    }
    foreach ($f in @($exe, $setup)) {
        $path = Join-Path $dest $f
        $info = (Get-Item $path).VersionInfo
        if ($info.FileVersion -ne $version) {
            throw "$f 缺少版本资源:期望 $version,实际 '$($info.FileVersion)'(build.rs 没编进资源段?)"
        }
        foreach ($n in @(16, 32, 48, 256)) {
            $handles = New-Object IntPtr[] 1
            $ids = New-Object uint32[] 1
            $count = [FolderDockIconProbe]::PrivateExtractIcons($path, 0, $n, $n, $handles, $ids, 1, 0)
            if ($count -lt 1 -or $handles[0] -eq [IntPtr]::Zero) {
                throw "$f 没有 $n px 图标资源(build.rs 没编进资源段?)"
            }
            [FolderDockIconProbe]::DestroyIcon($handles[0]) | Out-Null
        }
        Write-Host "    $f 图标与版本资源 OK($version)"
    }

    $zip = Join-Path $root "$Out/FolderDock-$version.zip"
    if (Test-Path $zip) { Remove-Item -Force $zip }
    Compress-Archive -Path $dest -DestinationPath $zip

    Write-Host "==> 发布目录:$dest"
    Get-ChildItem $dest | ForEach-Object { Write-Host ("    {0,-24} {1,10:N0} bytes" -f $_.Name, $_.Length) }
    Write-Host "==> 压缩包:$zip"
} finally {
    Pop-Location
}