$ErrorActionPreference = "Stop"

Write-Host "=================================================="
Write-Host "Step 02 - Configure Tongcheng Key for Hermes"
Write-Host "=================================================="
Write-Host ""

$gatewayBase = "https://omlx.hellotaiji.com/v1"
$installRoot = Join-Path $env:LOCALAPPDATA "TongchengHermes"
$venvDir = Join-Path $installRoot "venv"
$hermesExe = Join-Path $venvDir "Scripts\hermes.exe"
$hermesHome = Join-Path $env:USERPROFILE ".hermes"
$configPath = Join-Path $hermesHome "config.yaml"
$envPath = Join-Path $hermesHome ".env"

function Read-ApiKey {
  $key = Read-Host "Paste your Tongcheng API Key, starts with sk-tc_"
  $key = ($key -replace "\s", "")
  $key = $key.Replace([string][char]0x200B, "")
  $key = $key.Replace([string][char]0x200C, "")
  $key = $key.Replace([string][char]0x200D, "")
  $key = $key.Replace([string][char]0xFEFF, "")
  if (-not $key.StartsWith("sk-tc_")) {
    throw "Invalid key. It should start with sk-tc_."
  }
  return $key
}

function Test-GatewayKey([string]$apiKey) {
  Write-Host "Checking available models..."
  $headers = @{ Authorization = "Bearer $apiKey" }
  try {
    $response = Invoke-RestMethod -Uri ($gatewayBase + "/models") -Headers $headers -Method Get -TimeoutSec 30
  } catch {
    $statusCode = $null
    if ($_.Exception.Response) {
      $statusCode = [int]$_.Exception.Response.StatusCode
    }
    if ($statusCode -eq 401 -or $statusCode -eq 403) {
      throw "API Key is not valid or has expired. Please log in to https://omlx.hellotaiji.com/login, copy your latest API Key, then run this step again."
    }
    throw "Cannot connect to Tongcheng gateway. Please check the network and run this step again. Detail: $($_.Exception.Message)"
  }
  if (-not $response.data) {
    throw "No models returned. Please check whether this API Key has model permission or quota."
  }
  return @($response.data)
}

function Get-NumberOrDefault($value, [int]$default) {
  if ($null -eq $value) { return $default }
  try {
    $n = [int]$value
    if ($n -gt 0) { return $n }
  } catch {}
  return $default
}

function Write-HermesConfig([string]$apiKey, [object[]]$modelItems) {
  if (-not (Test-Path $hermesHome)) {
    New-Item -ItemType Directory -Path $hermesHome -Force | Out-Null
  }

  $models = @($modelItems | ForEach-Object { $_.id } | Where-Object { $_ })
  if ($models.Count -eq 0) {
    throw "No usable models returned. Please check this API Key."
  }

  $defaultModel = "tc-main"
  if ($models -notcontains $defaultModel) {
    $defaultModel = $models[0]
  }

  $modelLines = @()
  foreach ($item in $modelItems) {
    $model = $item.id
    if (-not $model) { continue }
    $safe = $model.Replace("'", "''")
    $cap = $item.capabilities
    if (-not $cap) { $cap = $item.public_capabilities }
    $contextLength = 64000
    if ($cap) {
      $contextLength = Get-NumberOrDefault $cap.context_window 64000
    }
    $modelLines += "      '$safe':"
    $modelLines += "        context_length: $contextLength"
    if ($cap -and ($cap.supports_vision -eq $true)) {
      $modelLines += "        supports_vision: true"
    }
  }
  $modelBlock = $modelLines -join "`n"

  $config = @"
model:
  provider: custom
  default: $defaultModel
  base_url: $gatewayBase
  api_key: $apiKey
  key_env: TONGCHENG_GATEWAY_API_KEY
  api_mode: chat_completions

providers:
  tongcheng:
    name: Tongcheng
    base_url: $gatewayBase
    api_key: $apiKey
    key_env: TONGCHENG_GATEWAY_API_KEY
    default_model: $defaultModel
    transport: chat_completions
    models:
$modelBlock

toolsets: []

agent:
  max_turns: 60
  api_max_retries: 2
  image_input_mode: auto
"@

  if (Test-Path $configPath) {
    $backup = "$configPath.$(Get-Date -Format 'yyyyMMdd_HHmmss').bak"
    Copy-Item -LiteralPath $configPath -Destination $backup -Force
    Write-Host "Backup: $backup"
  }
  Set-Content -LiteralPath $configPath -Value $config -Encoding UTF8

  $envContent = @"
TONGCHENG_GATEWAY_API_KEY=$apiKey
CUSTOM_BASE_URL=$gatewayBase
HERMES_INFERENCE_PROVIDER=custom
HERMES_INFERENCE_MODEL=$defaultModel
"@
  Set-Content -LiteralPath $envPath -Value $envContent -Encoding UTF8
}

if (-not (Test-Path $hermesExe)) {
  throw "Hermes is not installed. Please run 01_INSTALL_HERMES.cmd first."
}

$apiKey = Read-ApiKey
$modelItems = Test-GatewayKey $apiKey
$models = @($modelItems | ForEach-Object { $_.id } | Where-Object { $_ })
Write-Host "Available models:"
foreach ($m in $models) { Write-Host "  - $m" }
Write-HermesConfig $apiKey $modelItems

Write-Host ""
Write-Host "Hermes is configured."
Write-Host "Next: run 03_START_HERMES.cmd"
