param(
  # 要执行的命令：help / clean / build / server / preview / deploy
  [Parameter(Position=0)]
  [ValidateSet('help','clean','build','server','preview','deploy')]
  [string]$Command = 'help'
)

# 只要出现错误就立即停止，避免后续命令继续执行
$ErrorActionPreference = 'Stop'

# 以脚本所在目录为基准，切回博客根目录
$root = Split-Path -Parent $PSScriptRoot
Set-Location $root

# 环境变量可覆盖默认值
$port = if ($env:PORT) { $env:PORT } else { '4000' }
$hostName = if ($env:HOST) { $env:HOST } else { '127.0.0.1' }
$branch = if ($env:BRANCH) { $env:BRANCH } else { 'main' }

function Show-Usage {
@"
博客脚本用法：
  ./tools/blog.ps1 clean    # 清理缓存和 public 目录
  ./tools/blog.ps1 build    # 生成静态文件
  ./tools/blog.ps1 server   # 启动本地服务
  ./tools/blog.ps1 preview  # 清理 + 生成 + 启动预览
  ./tools/blog.ps1 deploy   # 清理 + 生成 + git 提交 + 推送

可选环境变量：
  PORT=4000         预览端口
  HOST=127.0.0.1    监听地址
  BRANCH=main       推送分支
"@
}

function Invoke-Hexo {
  # 把后续参数原样转发给 hexo
  param([Parameter(ValueFromRemainingArguments = $true)][string[]]$HexoArgs)

  & npx hexo @HexoArgs
  if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}

function Add-BlogFiles {
  # 只暂存博客相关文件，避免误把 node_modules、public 或其他杂项提交进去
  $paths = @(
    '_config.yml',
    '_config.butterfly.yml',
    '_config.landscape.yml',
    'package.json',
    'package-lock.json',
    'scaffolds',
    'source',
    'themes',
    'tools'
  )

  $existingPaths = @()
  foreach ($path in $paths) {
    if (Test-Path $path) {
      $existingPaths += $path
    }
  }

  if ($existingPaths.Count -eq 0) {
    Write-Host '[deploy] 没有找到可暂存的博客文件'
    exit 1
  }

  git add -- @existingPaths
  if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
}

switch ($Command) {
  'clean' {
    Write-Host '[clean] 清理生成缓存'
    Invoke-Hexo clean
  }
  'build' {
    Write-Host '[build] 生成静态文件'
    Invoke-Hexo generate
  }
  'server' {
    Write-Host "[server] 启动预览服务：http://${hostName}:${port}"
    Invoke-Hexo server -i $hostName -p $port
  }
  'preview' {
    Write-Host '[preview] 清理并生成静态文件'
    Invoke-Hexo clean
    Invoke-Hexo generate

    Write-Host "[preview] 启动预览服务：http://${hostName}:${port}"
    Invoke-Hexo server -i $hostName -p $port
  }
  'deploy' {
    Write-Host '[deploy] 清理并生成静态文件'
    Invoke-Hexo clean
    Invoke-Hexo generate

    Write-Host '[deploy] 只暂存博客相关改动'
    Add-BlogFiles

    # 没有变更就不提交也不推送
    git diff --cached --quiet
    if ($LASTEXITCODE -eq 0) {
      Write-Host '[deploy] 没有可提交的改动，跳过 commit/push'
      exit 0
    }

    $timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    Write-Host "[deploy] 提交改动：chore: deploy blog $timestamp"
    git commit -m "chore: deploy blog $timestamp"
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }

    Write-Host "[deploy] 推送到 origin/$branch"
    git push origin $branch
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
  }
  default {
    Show-Usage
  }
}
