<#
  SFCraft 文档构建入口: 先同步物品贴图, 再执行 hugo 构建。
  贴图同步失败(有物品找不到)时终止构建。
  用法: powershell -ExecutionPolicy Bypass -File scripts\build.ps1 [hugo 参数...]
#>
[CmdletBinding()]
param(
  [Parameter(ValueFromRemainingArguments = $true)]
  [string[]]$HugoArgs
)

$ErrorActionPreference = 'Stop'
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

function Get-HugoPath {
  if ($env:HUGO) { return $env:HUGO }
  $cmd = Get-Command hugo -ErrorAction SilentlyContinue
  if ($cmd) { return $cmd.Source }
  $p = Get-ChildItem -Path (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages') -Recurse -Filter hugo.exe -ErrorAction SilentlyContinue |
       Sort-Object LastWriteTime -Descending | Select-Object -First 1
  if ($p) { return $p.FullName }
  throw '未找到 Hugo。请安装 Hugo, 或将 hugo 可执行文件路径写入环境变量 HUGO。'
}

Write-Host "`n[1/2] 同步物品贴图" -ForegroundColor Cyan
& (Join-Path $scriptDir 'sync-items.ps1')
if ($LASTEXITCODE -ne 0) {
  Write-Host "[构建终止] 物品贴图同步失败, 未执行 hugo 构建。" -ForegroundColor Red
  exit $LASTEXITCODE
}

Write-Host "`n[2/2] hugo 构建" -ForegroundColor Cyan
$hugo = Get-HugoPath
& $hugo @HugoArgs
exit $LASTEXITCODE
