$ErrorActionPreference = "Stop"

Write-Host "=================================================="
Write-Host "Step 03 - Start Hermes"
Write-Host "=================================================="
Write-Host ""

$installRoot = Join-Path $env:LOCALAPPDATA "TongchengHermes"
$venvDir = Join-Path $installRoot "venv"
$pythonExe = Join-Path $venvDir "Scripts\python.exe"
$hermesExe = Join-Path $installRoot "venv\Scripts\hermes.exe"
$hermesHome = Join-Path $env:USERPROFILE ".hermes"
$configPath = Join-Path $hermesHome "config.yaml"
$envPath = Join-Path $hermesHome ".env"
$tuiEntry = Join-Path $venvDir "Lib\site-packages\hermes_cli\tui_dist\entry.js"
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$studentChat = Join-Path $scriptDir "student-chat.py"

function Read-HermesEnv {
  $values = @{}
  if (-not (Test-Path $envPath)) { return $values }
  foreach ($line in Get-Content -LiteralPath $envPath -Encoding UTF8) {
    if (-not $line -or $line.TrimStart().StartsWith("#") -or $line -notmatch "=") { continue }
    $parts = $line.Split("=", 2)
    $values[$parts[0].Trim()] = $parts[1].Trim()
  }
  return $values
}

function Get-TongchengApiKey([string]$configText) {
  $envValues = Read-HermesEnv
  foreach ($name in @("TONGCHENG_GATEWAY_API_KEY", "OPENAI_API_KEY")) {
    if ($envValues.ContainsKey($name)) {
      $candidate = [string]$envValues[$name]
      if ($candidate.StartsWith("sk-tc_")) { return $candidate }
    }
  }
  if ($configText -match "(?m)^\s*api_key:\s*(sk-tc_[^\s]+)\s*$") {
    return $Matches[1]
  }
  return ""
}

function Repair-TongchengProviderConfig {
  if (-not (Test-Path $configPath)) { return }
  $text = Get-Content -LiteralPath $configPath -Raw
  $original = $text
  $apiKey = Get-TongchengApiKey $text

  $text = $text -replace "(?m)^(\s*provider:\s*)custom:tongcheng\s*$", '${1}custom'

  if ($text -match "(?m)^model:\s*$") {
    if ($text -notmatch "(?m)^  base_url:\s*https://omlx\.hellotaiji\.com/v1\s*$") {
      $text = [regex]::Replace($text, "(?m)^(  default:\s*.+\r?\n)", "`$1  base_url: https://omlx.hellotaiji.com/v1`r`n", 1)
    }
    if ($apiKey -and $text -notmatch "(?m)^  api_key:\s*sk-tc_") {
      $text = [regex]::Replace($text, "(?m)^(  base_url:\s*https://omlx\.hellotaiji\.com/v1\s*\r?\n)", "`$1  api_key: $apiKey`r`n", 1)
    }
    if ($text -notmatch "(?m)^  key_env:\s*TONGCHENG_GATEWAY_API_KEY\s*$") {
      $text = [regex]::Replace($text, "(?m)^(  api_key:\s*.+\r?\n)", "`$1  key_env: TONGCHENG_GATEWAY_API_KEY`r`n", 1)
    }
    if ($text -notmatch "(?m)^  api_mode:\s*chat_completions\s*$") {
      $text = [regex]::Replace($text, "(?m)^(  key_env:\s*TONGCHENG_GATEWAY_API_KEY\s*\r?\n)", "`$1  api_mode: chat_completions`r`n", 1)
    }
  }

  if ($text -ne $original) {
    $backup = "$configPath.provider_backup_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
    Copy-Item -LiteralPath $configPath -Destination $backup -Force
    Set-Content -LiteralPath $configPath -Value $text -Encoding UTF8
    Write-Host "Updated Hermes provider config for Tongcheng gateway."
    Write-Host "Backup: $backup"
  }

  if ($apiKey) {
    $env:TONGCHENG_GATEWAY_API_KEY = $apiKey
    $env:CUSTOM_BASE_URL = "https://omlx.hellotaiji.com/v1"
    $env:HERMES_INFERENCE_PROVIDER = "custom"
    if (Test-Path "Env:\OPENAI_API_KEY") { Remove-Item "Env:\OPENAI_API_KEY" -ErrorAction SilentlyContinue }
    if (Test-Path "Env:\OPENAI_BASE_URL") { Remove-Item "Env:\OPENAI_BASE_URL" -ErrorAction SilentlyContinue }
    if (Test-Path "Env:\OPENROUTER_API_KEY") { Remove-Item "Env:\OPENROUTER_API_KEY" -ErrorAction SilentlyContinue }
    if (Test-Path "Env:\OPENROUTER_BASE_URL") { Remove-Item "Env:\OPENROUTER_BASE_URL" -ErrorAction SilentlyContinue }
    $model = "tc-main"
    if ($text -match "(?m)^  default:\s*([^\s]+)\s*$") { $model = $Matches[1] }
    $envContent = @"
TONGCHENG_GATEWAY_API_KEY=$apiKey
CUSTOM_BASE_URL=https://omlx.hellotaiji.com/v1
HERMES_INFERENCE_PROVIDER=custom
HERMES_INFERENCE_MODEL=$model
"@
    Set-Content -LiteralPath $envPath -Value $envContent -Encoding UTF8
  }
}

function Set-ChatOnlyConfig {
  if (-not (Test-Path $configPath)) { return }
  $text = Get-Content -LiteralPath $configPath -Raw
  $original = $text
  if ($text -match "(?ms)^toolsets:\s*\r?\n(?:[ \t]*-\s*.*\r?\n)*") {
    $text = [regex]::Replace($text, "(?ms)^toolsets:\s*\r?\n(?:[ \t]*-\s*.*\r?\n)*", "toolsets: []`r`n", 1)
  } elseif ($text -notmatch "(?m)^toolsets:") {
    $text = [regex]::Replace($text, "(?m)^agent:", "toolsets: []`r`n`r`nagent:", 1)
  }
  if ($text -ne $original) {
    $backup = "$configPath.chat_tools_backup_$(Get-Date -Format 'yyyyMMdd_HHmmss')"
    Copy-Item -LiteralPath $configPath -Destination $backup -Force
    Set-Content -LiteralPath $configPath -Value $text -Encoding UTF8
    Write-Host "Updated Hermes config for stable chat-only mode."
    Write-Host "Backup: $backup"
  }
}

if (-not (Test-Path $hermesExe)) {
  throw "Hermes is not installed. Please run 01_INSTALL_HERMES.cmd first."
}
if (-not (Test-Path $pythonExe)) {
  throw "Python venv is not installed. Please run 01_INSTALL_HERMES.cmd first."
}
if (-not (Test-Path $configPath)) {
  throw "Hermes is not configured. Please run 02_CONFIGURE_KEY.cmd first."
}

$env:HERMES_HOME = $hermesHome
$env:HERMES_IGNORE_RULES = "1"
Repair-TongchengProviderConfig
Set-ChatOnlyConfig
Write-Host ""
Write-Host "Choose how to open:"
Write-Host "  1  Student Chat mode (recommended)"
Write-Host "  2  Hermes Classic CLI mode (advanced)"
Write-Host "  3  TUI mode (experimental)"
Write-Host ""
$choice = Read-Host "Type 1, 2, or 3, then press Enter"

Write-Host ""
Write-Host "Tip: type /model to switch models."
Write-Host "Tip: use /image <image path> after switching to tc-multimodal for image input."
Write-Host ""

if ($choice -eq "3") {
  if (-not (Test-Path $tuiEntry)) {
    Write-Host "TUI files were not found in this Hermes package."
    Write-Host "Starting Student Chat mode instead..."
    & $pythonExe $studentChat
    exit $LASTEXITCODE
  }
  Write-Host "Starting Hermes TUI..."
  & $hermesExe --tui
} elseif ($choice -eq "2") {
    Write-Host "Starting Hermes classic CLI..."
    & $hermesExe -t none --ignore-rules
    exit $LASTEXITCODE
} else {
  if (-not (Test-Path $studentChat)) {
    throw "Student chat script not found: $studentChat"
  }
  Write-Host "Starting Student Chat mode..."
  & $pythonExe $studentChat
}
