Set-StrictMode -Version Latest

$Script:TencentNewsApiKeyEnv = "TENCENT_NEWS_APIKEY"
$Script:TencentNewsBaseDownloadUrl = "https://mat1.gtimg.com/qqcdn/qqnews/cli/hub"
$Script:TencentNewsDefaultUpdateWindowSeconds = 43200
$Script:TencentNewsScriptsDir = $PSScriptRoot
$Script:TencentNewsSkillDir = Split-Path -Parent $Script:TencentNewsScriptsDir

# Persistent config stored under $HOME/.config/tencent-news-cli/config.json
# Used as fallback when env var is not set (e.g. sandboxed agents).
$Script:TencentNewsConfigDir = Join-Path $HOME ".config" | Join-Path -ChildPath "tencent-news-cli"
$Script:TencentNewsConfigFile = Join-Path $Script:TencentNewsConfigDir "config.json"

function Write-TencentNewsJson {
  param(
    [Parameter(Mandatory = $true)]
    [object]$Value
  )

  $Value | ConvertTo-Json -Depth 8
}

function Fail-TencentNews {
  param(
    [Parameter(Mandatory = $true)]
    [string]$Message
  )

  [Console]::Error.WriteLine("Error: $Message")
  exit 1
}

function Get-TencentNewsPlatformInfo {
  $archRaw = if ($env:PROCESSOR_ARCHITEW6432) {
    $env:PROCESSOR_ARCHITEW6432
  } elseif ($env:PROCESSOR_ARCHITECTURE) {
    $env:PROCESSOR_ARCHITECTURE
  } else {
    [System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()
  }

  $arch = switch -Regex ($archRaw.ToLowerInvariant()) {
    "arm64|aarch64" { "arm64"; break }
    "amd64|x86_64" { "amd64"; break }
    default { throw "unsupported architecture: $archRaw" }
  }

  $cliFilename = "tencent-news-cli.exe"
  $cliPath = Join-Path $Script:TencentNewsSkillDir $cliFilename
  $cliDownloadUrl = "$($Script:TencentNewsBaseDownloadUrl)/windows-$arch/$cliFilename"
  $lastCheckFile = Join-Path $Script:TencentNewsSkillDir ".last-update-check-windows-$arch"

  [pscustomobject]@{
    os             = "windows"
    arch           = $arch
    detectedShell  = "powershell"
    preferredShell = "powershell"
    profilePath    = $PROFILE.CurrentUserCurrentHost
    cliFilename    = $cliFilename
    cliPath        = $cliPath
    cliDownloadUrl = $cliDownloadUrl
    lastCheckFile  = $lastCheckFile
    helpCommand    = "& '$cliPath' help"
    versionCommand = "& '$cliPath' version"
  }
}

function Read-TencentNewsConfigApiKey {
  if (-not (Test-Path -LiteralPath $Script:TencentNewsConfigFile)) {
    return $null
  }
  try {
    $cfg = Get-Content -LiteralPath $Script:TencentNewsConfigFile -Raw | ConvertFrom-Json
    $val = $cfg.$($Script:TencentNewsApiKeyEnv)
    if ($val) { return $val }
  } catch {}
  return $null
}

function Write-TencentNewsConfigApiKey {
  param(
    [Parameter(Mandatory = $true)]
    [string]$ApiKey
  )
  if (-not (Test-Path -LiteralPath $Script:TencentNewsConfigDir)) {
    New-Item -ItemType Directory -Path $Script:TencentNewsConfigDir -Force | Out-Null
  }
  @{ $Script:TencentNewsApiKeyEnv = $ApiKey } | ConvertTo-Json | Set-Content -LiteralPath $Script:TencentNewsConfigFile -Encoding UTF8
}

function Get-TencentNewsApiKeyState {
  param(
    [Parameter(Mandatory = $true)]
    [object]$PlatformInfo
  )

  $envPresent = [bool]$env:TENCENT_NEWS_APIKEY

  $result = [ordered]@{
    envVar     = $Script:TencentNewsApiKeyEnv
    present    = $envPresent
    configFile = $Script:TencentNewsConfigFile
  }

  if (-not $envPresent) {
    $cfgVal = Read-TencentNewsConfigApiKey
    if ($cfgVal) {
      $escaped = $cfgVal.Replace("'", "''")
      $result["configFileHasKey"] = $true
      $result["restoreCommand"] = "`$env:$($Script:TencentNewsApiKeyEnv) = '$escaped'"
    } else {
      $result["configFileHasKey"] = $false
    }
  }

  $result["detectedShell"] = $PlatformInfo.detectedShell
  $result["preferredShell"] = $PlatformInfo.preferredShell
  $result["profilePath"] = $PlatformInfo.profilePath
  $result["canAutoConfigure"] = $true
  $result["verificationCommand"] = '$env:TENCENT_NEWS_APIKEY'

  [pscustomobject]$result
}

function Read-TencentNewsLastCheckEpoch {
  param(
    [Parameter(Mandatory = $true)]
    [string]$Path
  )

  if (-not (Test-Path -LiteralPath $Path)) {
    return [int64]0
  }

  $raw = (Get-Content -LiteralPath $Path -Raw).Trim()
  if ($raw -notmatch '^\d+$') {
    return [int64]0
  }

  return [int64]$raw
}

function Write-TencentNewsLastCheckEpoch {
  param(
    [Parameter(Mandatory = $true)]
    [string]$Path,
    [int64]$Epoch = ([DateTimeOffset]::UtcNow.ToUnixTimeSeconds())
  )

  Set-Content -LiteralPath $Path -Value $Epoch
  return $Epoch
}

function Get-TencentNewsDownloadUrl {
  param(
    [Parameter(Mandatory = $true)]
    [object]$PlatformInfo,
    [string]$ExplicitUrl
  )

  if ($ExplicitUrl) {
    return $ExplicitUrl
  }

  return "$($Script:TencentNewsBaseDownloadUrl)/$($PlatformInfo.os)-$($PlatformInfo.arch)/$($PlatformInfo.cliFilename)"
}

function Download-TencentNewsCli {
  param(
    [Parameter(Mandatory = $true)]
    [string]$DownloadUrl,
    [Parameter(Mandatory = $true)]
    [object]$PlatformInfo
  )

  Invoke-WebRequest -Uri $DownloadUrl -OutFile $PlatformInfo.cliPath
}

function Get-TencentNewsCliVersion {
  param(
    [Parameter(Mandatory = $true)]
    [string]$CliPath
  )

  if (-not (Test-Path -LiteralPath $CliPath)) {
    throw "cli not found at $CliPath"
  }

  $rawOutput = (& $CliPath version 2>&1 | Out-String).Trim()
  if (-not $rawOutput) {
    throw "cli returned empty version output"
  }

  try {
    $parsed = $rawOutput | ConvertFrom-Json
  } catch {
    $parsed = $null
  }

  [pscustomobject]@{
    RawOutput = $rawOutput
    Parsed    = $parsed
  }
}

function Resolve-TencentNewsVersionDownloadUrl {
  param(
    [Parameter(Mandatory = $true)]
    [object]$VersionInfo,
    [Parameter(Mandatory = $true)]
    [object]$PlatformInfo
  )

  $key = "$($PlatformInfo.os)_$($PlatformInfo.arch)"
  $candidate = $VersionInfo.download_urls.$key

  if ($candidate) {
    return $candidate
  }

  return Get-TencentNewsDownloadUrl -PlatformInfo $PlatformInfo
}

function Set-TencentNewsApiKey {
  param(
    [Parameter(Mandatory = $true)]
    [string]$ApiKey
  )

  [Environment]::SetEnvironmentVariable($Script:TencentNewsApiKeyEnv, $ApiKey, "User")
  Write-TencentNewsConfigApiKey -ApiKey $ApiKey

  $escaped = $ApiKey.Replace("'", "''")

  [pscustomobject]@{
    configured          = $true
    present             = $true
    storage             = "windows-user-env"
    configFile          = $Script:TencentNewsConfigFile
    sessionCommand      = "`$env:$($Script:TencentNewsApiKeyEnv) = '$escaped'"
    verificationCommand = '$env:TENCENT_NEWS_APIKEY'
    requiresNewTerminal = $false
  }
}
