param(
  [string]$Set,
  [switch]$Help
)

if ($Help) {
  @"
Usage: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/api-key.ps1 [-Set KEY]

Inspect or persist the TENCENT_NEWS_APIKEY value 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 ($Set) {
    $result = Set-TencentNewsApiKey -ApiKey $Set
    Write-TencentNewsJson @{
      envVar              = $Script:TencentNewsApiKeyEnv
      present             = $true
      detectedShell       = $platform.detectedShell
      preferredShell      = $platform.preferredShell
      profilePath         = $platform.profilePath
      canAutoConfigure    = $true
      configured          = $true
      storage             = $result.storage
      configFile          = $result.configFile
      sessionCommand      = $result.sessionCommand
      verificationCommand = $result.verificationCommand
      requiresNewTerminal = $result.requiresNewTerminal
      note                = "Run sessionCommand in the current terminal if you need the key immediately."
    }
    exit 0
  }

  Write-TencentNewsJson (Get-TencentNewsApiKeyState -PlatformInfo $platform)
} catch {
  Fail-TencentNews $_.Exception.Message
}
