$ErrorActionPreference = "Stop"

Write-Host "=================================================="
Write-Host "Step 01 - Install Hermes"
Write-Host "=================================================="
Write-Host ""

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$packRoot = Split-Path -Parent $scriptDir
$offlineDir = Join-Path $packRoot "offline"
$pythonInstaller = Join-Path $offlineDir "python-3.12.10-amd64.exe"
$wheelsDir = Join-Path $offlineDir "wheels"
$installRoot = Join-Path $env:LOCALAPPDATA "TongchengHermes"
$venvDir = Join-Path $installRoot "venv"
$pythonExe = Join-Path $venvDir "Scripts\python.exe"
$hermesExe = Join-Path $venvDir "Scripts\hermes.exe"

function Warn-NonAsciiPath([string]$path) {
  if ($path -match "[^\x00-\x7F]") {
    Write-Host "WARNING: This installer is in a non-English path:"
    Write-Host "  $path"
    Write-Host "If installation fails, move the whole folder to D:\tc-hermes and run again."
  }
}

function Find-Python {
  $candidates = @(
    "$env:LOCALAPPDATA\Programs\Python\Python312\python.exe",
    "$env:ProgramFiles\Python312\python.exe",
    "${env:ProgramFiles(x86)}\Python312\python.exe"
  )
  foreach ($candidate in $candidates) {
    if ($candidate -and (Test-Path $candidate)) { return $candidate }
  }
  $cmd = Get-Command python -ErrorAction SilentlyContinue
  if ($cmd -and $cmd.Source) {
    try {
      $version = & $cmd.Source -c "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')"
      if ($version -eq "3.12") { return $cmd.Source }
    } catch {}
  }
  return $null
}

function Ensure-Python {
  $py = Find-Python
  if ($py) {
    Write-Host "Python is ready: $py"
    return $py
  }
  if (-not (Test-Path $pythonInstaller)) {
    throw "Missing offline Python installer: $pythonInstaller"
  }
  Write-Host "Installing bundled Python 3.12..."
  $args = @(
    "/quiet",
    "InstallAllUsers=0",
    "PrependPath=0",
    "Include_test=0",
    "Include_launcher=0",
    "Include_pip=1",
    "Include_doc=0"
  )
  $p = Start-Process -FilePath $pythonInstaller -ArgumentList $args -Wait -PassThru
  if ($p.ExitCode -ne 0) {
    throw "Python installer failed with exit code $($p.ExitCode)."
  }
  $py = Find-Python
  if (-not $py) {
    throw "Python was installed, but python.exe was not found."
  }
  Write-Host "Python installed: $py"
  return $py
}

function Ensure-Wheels {
  if (-not (Test-Path $wheelsDir)) {
    throw "Missing wheels folder: $wheelsDir"
  }
  $required = @(
    "hermes_agent-0.14.0-py3-none-any.whl",
    "colorama-0.4.6-py2.py3-none-any.whl",
    "openai-2.24.0-py3-none-any.whl",
    "pydantic-2.12.5-py3-none-any.whl",
    "pydantic_core-2.41.5-cp312-cp312-win_amd64.whl",
    "tzdata-2025.3-py2.py3-none-any.whl",
    "pyyaml-6.0.3-cp312-cp312-win_amd64.whl"
  )
  foreach ($name in $required) {
    if (-not (Test-Path (Join-Path $wheelsDir $name))) {
      throw "Offline dependency is incomplete. Missing: $name"
    }
  }
}

Warn-NonAsciiPath $packRoot
Ensure-Wheels
$systemPython = Ensure-Python

if (-not (Test-Path $installRoot)) {
  New-Item -ItemType Directory -Path $installRoot -Force | Out-Null
}

if (-not (Test-Path $pythonExe)) {
  Write-Host "Creating Hermes virtual environment..."
  & $systemPython -m venv $venvDir
  if ($LASTEXITCODE -ne 0) { throw "Failed to create Python virtual environment." }
}

Write-Host "Installing Hermes from offline files..."
& $pythonExe -m pip install --no-index --find-links $wheelsDir --upgrade hermes-agent==0.14.0
if ($LASTEXITCODE -ne 0) { throw "Failed to install Hermes offline wheels." }

if (-not (Test-Path $hermesExe)) {
  throw "Hermes executable was not created: $hermesExe"
}

Write-Host ""
Write-Host "Hermes is ready."
Write-Host "Next: run 02_CONFIGURE_KEY.cmd"
