param(
  [switch]$Apply,
  [switch]$Help
)

if ($Help) {
  @"
Usage: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/check-update.ps1 [-Apply]

Inspect the CLI version JSON and optionally download the newer binary for Windows.
"@
  exit 0
}

$commonScript = Join-Path $PSScriptRoot "_common.ps1"
if (-not (Test-Path -LiteralPath $commonScript)) {
  $commonScript = Join-Path $PSScriptRoot "_common.txt"
}
. $commonScript

try {
  $platform = Get-TencentNewsPlatformInfo
  if (-not (Test-Path -LiteralPath $platform.cliPath)) {
    Fail-TencentNews "cli not found at $($platform.cliPath). Run powershell -NoProfile -ExecutionPolicy Bypass -File scripts/install-cli.ps1 first."
  }

  $before = Get-TencentNewsCliVersion -CliPath $platform.cliPath
  if (-not $before.Parsed) {
    Fail-TencentNews "`version` did not return valid JSON."
  }

  $downloadUrl = Resolve-TencentNewsVersionDownloadUrl -VersionInfo $before.Parsed -PlatformInfo $platform
  $applied = $false
  $after = $before

  if ($Apply -and $before.Parsed.need_update) {
    Download-TencentNewsCli -DownloadUrl $downloadUrl -PlatformInfo $platform
    $after = Get-TencentNewsCliVersion -CliPath $platform.cliPath
    $applied = $true
  }

  $checkedAt = Write-TencentNewsLastCheckEpoch -Path $platform.lastCheckFile

  Write-TencentNewsJson @{
    platform            = $platform
    checkedAt           = $checkedAt
    needUpdate          = [bool]$before.Parsed.need_update
    applied             = $applied
    selectedDownloadUrl = $downloadUrl
    currentVersion      = $after.Parsed.current_version
    latestVersion       = $before.Parsed.latest_version
    releaseNotes        = $before.Parsed.release_notes
    rawBefore           = $before.RawOutput
    rawAfter            = $after.RawOutput
  }
} catch {
  Fail-TencentNews $_.Exception.Message
}
