<#
  SFCraft 文档开发服务器入口: 先同步物品贴图, 再启动 hugo server。
  贴图同步失败(有物品找不到)时终止启动。
  用法: powershell -ExecutionPolicy Bypass -File scripts\dev.ps1 [-NoSync] [hugo server 参数...]
#>
[CmdletBinding()]
param(
  [switch]$NoSync,
  [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。'
}

if (-not $NoSync) {
  Write-Host "`n[1/2] 同步物品贴图" -ForegroundColor Cyan
  & (Join-Path $scriptDir 'sync-items.ps1')
  if ($LASTEXITCODE -ne 0) {
    Write-Host "[启动终止] 物品贴图同步失败, 未启动 hugo server。" -ForegroundColor Red
    exit $LASTEXITCODE
  }
} else {
  Write-Host "[跳过] 已指定 -NoSync, 不执行贴图同步" -ForegroundColor Yellow
}

Write-Host "`n[2/2] 启动 hugo server" -ForegroundColor Cyan
$hugo = Get-HugoPath
$serverArgs = @('server')
if ($HugoArgs.Count -gt 0) { $serverArgs += $HugoArgs }
& $hugo @serverArgs
exit $LASTEXITCODE
